[Leetcode] Search in Rotated Sorted Array II
2014-10-21 03:07
309 查看
题目:
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.
思路:二分法。类似Search in Rotated Sorted Array I,先确定哪边是连续的,然后通过连续的那部分去判断需要向左还是向右。唯一的区别在于,由于有duplicated元素存在,可能导致无法判断哪边是连续的。例如,A[] = {2, 2, 1, 2},这时A[lower_bound] == A[mid] == A[upper_bound],现有的判断哪边是连续的条件在这里会失效。这里的做法是,由于已经判断完A[mid]
!= target,因此无论上界还是下界都是没有用的字符,所以可以将当前区间shrink.
总结:复杂度为O(logn).
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.
思路:二分法。类似Search in Rotated Sorted Array I,先确定哪边是连续的,然后通过连续的那部分去判断需要向左还是向右。唯一的区别在于,由于有duplicated元素存在,可能导致无法判断哪边是连续的。例如,A[] = {2, 2, 1, 2},这时A[lower_bound] == A[mid] == A[upper_bound],现有的判断哪边是连续的条件在这里会失效。这里的做法是,由于已经判断完A[mid]
!= target,因此无论上界还是下界都是没有用的字符,所以可以将当前区间shrink.
class Solution { public: bool search(int A[], int n, int target) { int lower_bound = 0; int upper_bound = n - 1; while (lower_bound <= upper_bound) { int mid = (lower_bound + upper_bound) / 2; if (A[mid] == target) { return true; } else if (A[lower_bound] == A[mid] && A[upper_bound] == A[mid]) { //shrink lower_bound++; upper_bound--; } else if (A[lower_bound] <= A[mid]) { //left part consistent if (A[lower_bound] <= target && A[mid] > target) { //go left upper_bound = mid - 1; } else { lower_bound = mid + 1; } } else { //right part consistent if (A[upper_bound] >= target && A[mid] < target) { lower_bound = mid + 1; } else { upper_bound = mid - 1; } } } return false; } };
总结:复杂度为O(logn).
相关文章推荐
- [LeetCode] Search in Rotated Sorted Array II
- 【Leetcode】Search in Rotated Sorted Array II
- leetcode_Search in Rotated Sorted Array II
- [leetcode] Search in Rotated Sorted Array II
- Search in Rotated Sorted Array II [LeetCode]
- LeetCode-Search in Rotated Sorted Array II
- leetcode 98: Search in Rotated Sorted Array II
- LeetCode Online Judge 题目C# 练习 - Search in Rotated Sorted Array II
- 【leetcode】Search in Rotated Sorted Array II
- [LeetCode] Search in Rotated Sorted Array II 解题报告
- [Leetcode] Search in Rotated Sorted Array II
- LeetCode-Search in Rotated Sorted Array II
- leetcode Search in Rotated Sorted Array II
- LeetCode Search in Rotated Sorted Array II
- LeetCode - Search in Rotated Sorted Array II
- LeetCode : Search in Rotated Sorted Array II
- 【Leetcode】Search in Rotated Sorted Array II
- leetcode - Search in Rotated Sorted Array II
- [LeetCode] Search in Rotated Sorted Array II
- [LeetCode]Search in Rotated Sorted Array II