[LeetCode] Search in Rotated Sorted Array II
2013-11-05 10:25
417 查看
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,这里数组中可能会用重复元素。写一个函数判断一个给定的元素是否在数组中。对于“重复”这一条件会如何影响时间复杂度,为什么?
如果是采用顺序查找的方式那么就没有什么影响,但如果是采用二分或者其它的方法,就可能产生影响,因为,当采用二分查找时,根据查找元素与中间元素的比较有时不能确定是在左边查找还是在右边查找。这里先给出采用顺序查找的方法:
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,这里数组中可能会用重复元素。写一个函数判断一个给定的元素是否在数组中。对于“重复”这一条件会如何影响时间复杂度,为什么?
如果是采用顺序查找的方式那么就没有什么影响,但如果是采用二分或者其它的方法,就可能产生影响,因为,当采用二分查找时,根据查找元素与中间元素的比较有时不能确定是在左边查找还是在右边查找。这里先给出采用顺序查找的方法:
class Solution { public: bool search(int A[], int n, int target) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int i = 0; if(target > A[0]) { i = 1; while(i < n && A[i-1] <= A[i] && target > A[i]) ++i; if(target == A[i]) return true; return false; } else if(target < A[0]) { i = n - 1; while(i > 0 && A[i-1] <= A[i] && target < A[i]) --i; if(target == A[i]) return true; return false; } else { return true; } } };
相关文章推荐
- LeetCode | Search in Rotated Sorted Array II
- [LeetCode]81 Search in Rotated Sorted Array II
- [Leetcode] Search in Rotated Sorted Array II
- 【LeetCode】Search in Rotated Sorted Array && Search in Rotated Sorted Array II
- Leetcode 33, 81 Search in Rotated Sorted Array I, II
- LeetCode Online Judge 题目C# 练习 - Search in Rotated Sorted Array II
- [LeetCode]Search in Rotated Sorted Array II
- 【Leetcode】碰到一道脑残leetcode,比之前觉得简单的还简单。。。一下还两道……Search in Rotated Sorted Array I和II
- [leetcode]【数组】81. Search in Rotated Sorted Array II
- Leetcode_search-in-rotated-sorted-array-ii(updated c++ and python version)
- [leetcode]81. Search in Rotated Sorted Array II(Java)
- 154. Find Minimum in Rotated Sorted Array II leetcode binary search
- Search in Rotated Sorted Array II-LeetCode
- 081 Search in Rotated Sorted Array II[Leetcode]
- [leetcode] Search in Rotated Sorted Array II
- Leetcode: Search in Rotated Sorted Array II
- [leetcode]81. 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 和Search in Rotated Sorted Array II