-
Notifications
You must be signed in to change notification settings - Fork 0
/
SearchInsertPosition
55 lines (48 loc) · 1.25 KB
/
SearchInsertPosition
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// 1, https://leetcode.com/problems/search-insert-position/description/
// write in c++ and java
// www.cplusplus.com for vector, string ... usage
// cpp
class Solution{
public:
int searchInsert(vector<int>& nums, int target) {
int size = nums.size();
int left = 0;
int right = size;
int mid = 0;
while(left < right){
mid = (left + right)/2;
if(nums[mid] == target){
return mid;
} else if(target < nums[mid]){
right = mid;
} else if(target > nums[mid]){
left = mid + 1;
}
}
return right;
}
};
// java
class Solution {
public int searchInsert(int[] nums, int target) {
int size = nums.length;
int left = 0;
int right = size - 1;
int mid = 0;
while(left <= right){
mid = (left + right + 1)/2;
if(target == nums[mid]){
return mid;
} else if(target < nums[mid]){
right = mid - 1;
} else if(target > nums[mid]){
left = mid + 1;
}
}
if(target > nums[mid]){
return mid + 1;
} else{
return mid;
}
}
}