[LeetCode]Search in Rotated Sorted Array II
2013-06-01 09:45
399 查看
class Solution { //classified discussion //1. Based on the property of rotated array, there may or may not have one sorted sequence //when one sequence is divided into two parts //2. make decision under all these cases public: bool search(int A[], int n, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function return BinarySearch(A, n, target); } bool BinarySearch( int* A, int n, int target ) { //throw std::exception("The method or operation is not implemented."); int l = 0; int r = n-1; while (l <= r) { int m = l+(r-l)/2; if(A[m] == target) return true; if (A[l] < A[m])//left subsequence sorted { if(A[l] <= target && target < A[m]) r = m-1; else l = m+1; } else if (A[m] < A[r]) { if(A[m] < target && target <= A[r]) l = m+1; else r = m-1; } else if (A[l] == A[m])//A[m] is not the target, so remove en element equal to A[m] is safe l++; else if(A[m] == A[r])//ditto r--; } return false; } };
second time
class Solution { public: bool search(int A[], int n, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function int left = 0; int right = n-1; while(left <= right) { int mid = left+(right-left)/2; if(A[left] < target && target < A[mid]) right = mid-1; else if(A[mid] < target && target < A[right]) left = mid+1; else { if(A[left] != target) left++; else return true; if(A[right] != target) right--; else return true; } } } };
相关文章推荐
- 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-面试算法经典-Java实现】【081-Search in Rotated Sorted Array II(搜索旋转的排序数组)】
- leetcode 刷题之路 35 Search in Rotated Sorted Array II (旋转排序数组查找终极版)
- leetcode -- Search in Rotated Sorted Array I &II 重点可以考
- [LeetCode] Search in Rotated Sorted Array II 在旋转有序数组中搜索之二
- leetcode || 81、Search in Rotated Sorted Array II
- LeetCode Search in Rotated Sorted Array II
- leetcode刷题系列C++-Search in Rotated Sorted Array II
- LeetCode 81. 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 - Refresh - Search in Rotated Sorted Array II
- leetcode 081 Search in Rotated Sorted Array II
- Leetcode 81. Search in Rotated Sorted Array II (Medium) (cpp)
- 81. Search in Rotated Sorted Array II Leetcode Python