-
Notifications
You must be signed in to change notification settings - Fork 0
/
035. search in a sorted array of unknown size.cpp
45 lines (40 loc) · 1.24 KB
/
035. search in a sorted array of unknown size.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
702. Search in a Sorted Array of Unknown Size - LeetCode(Premium)
Given an integer array sorted in ascending order, write a function to search target in nums.
If target exists, then return its index, otherwise return -1. However, the array size is unknown to you.
Note:
You may assume that all elements in the array are unique.
The value of each element in the array will be in the range [-9999, 9999].
The given array is always sorted.
Input:
array = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation:
9 exists in nums and its index is 4
Code:
class Solution {
private:
int binarySearch(int nums[], int start, int end, int target) {
int mid = start + (end - start) / 2;
while (start <= end) {
if (nums[mid] == target)
return mid;
else if (nums[mid] < target)
start = mid + 1;
else
end = mid - 1;
}
return -1;
}
public:
int findIndexPosition(int nums[], int target) {
int start = 0;
int end = 1;
int value = nums[0];
while (value < target) {
start = end;
end = end * 2;
value = nums[end];
}
return binarySearch(nums, start, end, target);
}
};