LeetCode Search in Rotated Sorted Array II
2015-02-02 19:43
155 查看
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.
思路:算法最坏情况时间复杂度O(n),平均O(logn)。
还是Search
in Rotated Sorted Array的算法,算法走到A[i] == A[j] && i != j的情况时,无法再判断左右,此时只能全部扫描一遍。
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 i = 0, j = n - 1, m = (i + j) / 2; bool flag = false; while(i <= j) { if(i != j && A[i] == A[j]) { flag = true; break; } if(A[i] <= A[j]) { if(target == A[m]) return true; else if(target > A[m]) i = m + 1; else j = m - 1; } else { if(A[m] > A[j]) { if(target == A[m]) return true; if(target >= A[i] && target < A[m]) j = m - 1; else i = m + 1; } else { if(target == A[m]) return true; if(target > A[m] && target <= A[j]) i = m + 1; else j = m - 1; } } m = (i + j) / 2; } if(flag) { for(int k = i; k <= j; k++) { if(A[k] == target) return true; } } return false; } };
思路:算法最坏情况时间复杂度O(n),平均O(logn)。
还是Search
in Rotated Sorted Array的算法,算法走到A[i] == A[j] && i != j的情况时,无法再判断左右,此时只能全部扫描一遍。
相关文章推荐
- [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