LeetCode:Search in Rotated Sorted Array
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. 本文地址
分析:顺序查找肯定是可以的,可不可以找出效率更高的查找算法?其实二分查找也可以用在这里。那么和普通的二分查找有什么区别呢?
a、查找区间的尾部元素小于首部元素,这表示查找区间不是全部有序的,
b、target不大于查找区间的尾部元素,这表示target在旋转前数组的前半部分,
c、中间元素要大于查找区间尾部元素,这表示中间元素在旋转前数组的后半部分。
如果没有同时满足这三个条件那么我们要去middle的前半段查找。
a、查找区间的尾部元素小于首部元素,这表示查找区间不是全部有序的
b、target大于查找区间的尾部元素,这表示target在旋转前数组的后半部分
c、中间元素要小于查找区间尾部元素,这表示中间元素在旋转前数组的前半部分。
如果没有同时满足这三个条件那么我们要去middle的后半段查找。
class Solution { public: int search(int A[], int n, int target) { int istart = 0, iend = n-1, mid; while(istart <= iend) { mid = (istart + iend) / 2; if(A[mid] > target) { if(A[iend] < A[istart] && target <= A[iend] && A[mid] > A[iend]) istart = mid + 1; else iend = mid - 1; } else if(A[mid] < target) { if(A[iend] < A[istart] && target > A[iend] && A[mid] < A[iend]) iend = mid - 1; else istart = mid + 1; } else return mid; } return -1; } };
LeetCode: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.
分析:上一题的所有分析是基于数组中没有重复元素的,如果存在重复元素,情况会如何呢?
class Solution { public: bool search(int A[], int n, int target) { int istart = 0, iend = n-1, mid; while(istart <= iend) { mid = (istart + iend) / 2; if(A[mid] > target) { if(A[iend] <= A[istart] && target <= A[iend] && A[mid] >= A[iend]) { if(A[mid] == A[iend]) iend--; else istart = mid + 1; } else iend = mid - 1; } else if(A[mid] < target) { if(A[iend] <= A[istart] && target > A[iend] && A[mid] <= A[iend]) { if(A[mid] == A[iend]) iend--; else iend = mid - 1; } else istart = mid + 1; } else return true; } return false; } };
在leetcode的discuss里看到了另一种思路的解法,通过判断查找区间首部元素和中间元素的关系来判断查找区间的哪一部分是有序的
没有重复元素的情形下:
包含重复元素的情形:
两题都可以用以下代码(稍微修改返回值)
class Solution { public: bool search(int A[], int n, int key) { int l = 0, r = n - 1; while (l <= r) { int m = l + (r - l)/2; if (A[m] == key) return true; //return m in Search in Rotated Array I if (A[l] < A[m]) { //left half is sorted if (A[l] <= key && key < A[m]) r = m - 1; else l = m + 1; } else if (A[l] > A[m]) { //right half is sorted if (A[m] < key && key <= A[r]) l = m + 1; else r = m - 1; } else l++; } return false; } };
参考资料:http://oj.leetcode.com/discuss/223/when-there-are-duplicates-the-worst-case-is-could-we-do-better
【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3465240.html