8000 :rocket: 08-Oct-2020 · codezoned/Code@ec42565 · GitHub
[go: up one dir, main page]

Skip to content

Commit ec42565

Browse files
committed
🚀 08-Oct-2020
1 parent c4b1647 commit ec42565

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1.
2+
3+
4+
Example 1:
5+
6+
Input: nums = [-1,0,3,5,9,12], target = 9
7+
Output: 4
8+
Explanation: 9 exists in nums and its index is 4
9+
10+
Example 2:
11+
12+
Input: nums = [-1,0,3,5,9,12], target = 2
13+
Output: -1
14+
Explanation: 2 does not exist in nums so return -1
15+
16+
17+
Note:
18+
19+
You may assume that all elements in nums are unique.
20+
n will be in the range [1, 10000].
21+
The value of each element in nums will be in the range [-9999, 9999].
22+
23+
24+
25+
26+
27+
28+
class Solution {
29+
public:
30+
int search(vector<int>& nums, int target) {
31+
int start=0, end=nums.size()-1;
32+
33+
while(start<=end){
34+
int mid=start+(end-start)/2;
35+
if(nums[mid]==target) return mid;
36+
else if(nums[mid]>target) end=mid-1;
37+
else start=mid+1;
38+
}
39+
return -1;
40+
}
41+
};
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1.
2+
3+
4+
Example 1:
5+
6+
Input: nums = [-1,0,3,5,9,12], target = 9
7+
Output: 4
8+
Explanation: 9 exists in nums and its index is 4
9+
10+
Example 2:
11+
12+
Input: nums = [-1,0,3,5,9,12], target = 2
13+
Output: -1
14+
Explanation: 2 does not exist in nums so return -1
15+
16+
17+
Note:
18+
19+
You may assume that all elements in nums are unique.
20+
n will be in the range [1, 10000].
21+
The value of each element in nums will be in the range [-9999, 9999].
22+
23+
24+
25+
26+
27+
28+
class Solution {
29+
public:
30+
int search(vector<int>& nums, int target) {
31+
int start=0, end=nums.size()-1;
32+
33+
while(start<=end){
34+
int mid=start+(end-start)/2;
35+
if(nums[mid]==target) return mid;
36+
else if(nums[mid]>target) end=mid-1;
37+
else start=mid+1;
38+
}
39+
return -1;
40+
}
41+
};

0 commit comments

Comments
 (0)
0