Code & Func
2017-10-11

第18天!!!

又是一道二分查找的题目:

Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm’s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example, Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4].

时间复杂度要求为O(logn),直接就暗示我们要用二分查找去做啊,但是这个又有限定条件,就是它需要求出范围,自然而然的就想到先用二分查找,然后从找到的点向两边去寻找边界。

相当简单的方法,但是如果遇到1,2,2,2,2,2,2,2,3这样的序列,就变成了O(n)的时间复杂度。

然后就可以自然而然的想到,做多两次二分查找,在序列nums[0:mid]中寻找左边界,nums[mid:]中寻找右边界,不然如果要是用二分查找的方法去做的话,就需要转换一下,我们找左边界的前一个元素,右边界的后一个元素,这样会方便一点。

1
vector<int> searchRange1(vector<int>& nums, int target) {
2
int first = 0,last = nums.size() - 1,mid;
3
vector<int> ret{-1,-1};
4
while(first <= last) {
5
mid = (first + last)/2;
6
if (nums[mid] == target){
7
break;
8
}
9
else if (nums[mid] < target) first = mid+1;
10
else last = mid - 1;
11
}
12
13
int l = mid,f = mid;
14
ret[0] = first;
15
ret[1] = last;
23 collapsed lines
16
17
while(first <= l) {
18
int m = (first + l)/2;
19
if (nums[m] == nums[mid])
20
l = m - 1;
21
else if (nums[m+1] != nums[mid]) first = m + 1;
22
else {
23
ret[0] = m+1;
24
break;
25
}
26
}
27
while(f <= last) {
28
int m = (f + last)/2;
29
if (nums[m] == nums[mid]) f = m + 1;
30
else if (nums[m-1] != nums[mid]) last = m - 1;
31
else {
32
ret[1] = m - 1;
33
break;
34
}
35
}
36
37
return ret;
38
}

这个思路很简单,也很好实现,就是代码会复杂一点,三个循环其实长得差不多,但是你不能合并起来,所以换一种思路尝试一下:

我们找到一个与target相等的值nums[mid],我们对nums[0,mid-1]再进行一次二分查找:

  • 如果查找失败, 那么说明当前mid就是左边界
  • 如果找到了,我们就更新mid,再对nums[0:mid-1]进行查找,直到查找失败。

对右边界做同样的事,我们就得到答案了。

1
vector<int> searchRange(vector<int>& nums, int target) {
2
vector<int> ret{-1,-1};
3
int mid = nums.size();
4
while( (mid = searchRangeIter(nums,0,mid-1,target) ) != -1)
5
ret[0] = mid;
6
//mid = -1;
7
while( (mid = searchRangeIter(nums,mid+1,nums.size() - 1,target)) != -1)
8
ret[1] = mid;
9
return ret;
10
}
11
int searchRangeIter(vector<int> nums,int first,int last,int target) {
12
while(first <= last) {
13
int mid = (first + last)/2;
14
if (nums[mid] == target){
15
return mid;
6 collapsed lines
16
}
17
else if (nums[mid] < target) first = mid+1;
18
else last = mid - 1;
19
}
20
return -1;
21
}

dicuss中看到一个更简洁的迭代的方法:

1
vector<int> searchRange(int A[], int n, int target) {
2
int i = 0, j = n - 1;
3
vector<int> ret(2, -1);
4
// Search for the left one
5
while (i < j)
6
{
7
int mid = (i + j) /2;
8
if (A[mid] < target) i = mid + 1;
9
else j = mid;
10
}
11
if (A[i]!=target) return ret;
12
else ret[0] = i;
13
14
// Search for the right one
15
j = n-1; // We don't have to set i to 0 the second time.
9 collapsed lines
16
while (i < j)
17
{
18
int mid = (i + j) /2 + 1;// Make mid biased to the right
19
if (A[mid] > target) j = mid - 1;
20
else i = mid;// So that this won't make the search range stuck.
21
}
22
ret[1] = j;
23
return ret;
24
}
上一条动态