您的位置:首页 > 其它

Leetcode | Search in Rotated Sorted Array I & II

2014-05-18 19:36 661 查看

Search in Rotated Sorted Array I

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

Have you been asked this question in an interview?

二分查找。

1. 如果A[mid]>A[l],也就是A[l...mid]是递增序。如果target>=A[l]&&target<A[mid],那么target只可能在[l...mid-1]这个区间上,否则在[mid+1...h]这个区间。

2. 如果A[mid]<=A[l],那么A[mid...h]是递增序。如果target>A[mid] && target<=A[h],那么target只可能在[mid+1...h]这个区间,否则在[l...mid-1]这个区间。

class Solution {
public:
int search(int A[], int n, int target) {
if (n == 0) return -1;
int l = 0, h = n - 1, mid;

while (l <= h) {
mid = (l + h) / 2;
if (A[mid] == target) return mid;
if (A[mid] >= A[l]) {
if (target >= A[l] && target < A[mid]) {
h = mid - 1;
} else {
l = mid + 1;
}
} else {
if (target > A[mid] && target <= A[h]) {
l = mid + 1;
} else {
h = mid - 1;
}
}
}

return -1;
}
};


Search in Rotated Sorted Array II

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is in the array.

有了重复数。那么前面的情况,只对应于A[mid]>A[l]和A[mid]<A[l]是成立的。对于A[mid]==A[l],我们无法确定该数是在左区间还是右区间,反正一定不会是在A[l]上,所以l++。

最坏情况就是整个数组都是同一个数,target不在数组中,这样每次都只能l++,算法复杂度是O(n)。

class Solution {
public:
bool search(int A[], int n, int target) {
if (n == 0) return false;
int l = 0, h = n - 1, mid;

while (l <= h) {
mid = (l + h) / 2;
if (A[mid] == target) return true;
if (A[mid] == A[l]) {
l++;
} else if (A[mid] > A[l]) {
if (target >= A[l] && target < A[mid]) {
h = mid - 1;
} else {
l = mid + 1;
}
} else {
if (target > A[mid] && target <= A[h]) {
l = mid + 1;
} else {
h = mid - 1;
}
}
}

return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: