-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path457.classical-binary-search.cpp
87 lines (78 loc) · 1.77 KB
/
457.classical-binary-search.cpp
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Tag: Binary Search
// Time: O(logN)
// Space: O(1)
// Ref: -
// Note: -
// Find any position of a target number in a sorted array.
// Return `-1` if target does not exist.
//
// ---
//
//
// **Example 1:**
// ```
// Input: nums = [1,2,2,4,5,5], target = 2
// Output: 1 or 2
// ```
// **Example 2:**
// ```
// Input: nums = [1,2,2,4,5,5], target = 6
// Output: -1
// ```
//
//
class Solution {
public:
/**
* @param nums: An integer array sorted in ascending order
* @param target: An integer
* @return: An integer
*/
int findPosition(vector<int> &nums, int target) {
// write your code here
int n = nums.size();
int start = 0;
int end = n;
while (start < end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target) {
return mid;
}
if (nums[mid] < target) {
start = mid + 1;
} else {
end = mid;
}
}
return -1;
}
};
class Solution {
public:
/**
* @param nums: An integer array sorted in ascending order
* @param target: An integer
* @return: An integer
*/
int findPosition(vector<int> &nums, int target) {
// write your code here
int n = nums.size();
if (n == 0) {
return -1;
}
int left = 0;
int right = n - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
}
if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid;
}
}
return nums[left] == target ? left : -1;
}
};