LeetCode: Search in Rotated Sorted Array II
来源:互联网 发布:window 查看端口 编辑:程序博客网 时间:2024/06/08 16:41
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 left = 0, right = n-1, mid = 0; while(left <= right) { mid = (left+right) / 2; if(A[mid] == target) return true; if(A[mid] > A[left]) { if(target >= A[left] && target <= A[mid]) right = mid-1; else left = mid+1; } else if(A[mid] < A[left]) { if(target >= A[mid] && target <= A[right]) left = mid+1; else right = mid-1; } else left++; } return false; }};
Round 2:
class Solution {public: bool search(int A[], int n, int target) { return binarySearch(0, n-1, A, target); }private:bool binarySearch(int l, int r, int A[], int target){if(l > r)return false;int mid = (l + r) /2;if(A[mid] == target)return true;if(A[mid] == A[l] && A[mid] == A[r])return binarySearch(l+1, r-1, A, target);else if(A[mid] == A[r]){return binarySearch(l, r-1, A, target);}else if(A[mid] == A[l]){return binarySearch(l+1, r, A, target);}else{if(A[mid] < A[r]){if(target < A[mid] || (target > A[mid] && target > A[r]))return binarySearch(l, mid-1, A, target);elsereturn binarySearch(mid+1, r, A, target);}else{if(target > A[mid] || (target < A[mid] && target < A[l]))return binarySearch(mid+1, r, A, target);elsereturn binarySearch(l, mid-1, A, target);}}}};
0 0
- 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
- 【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
- 飘逸的python - 实现控制台进度条效果
- 百钱百鸡
- C/C++资源(源码、开发工具、开发库)
- 分治策略
- Institutional Aims and Learning Outcomes of PhD Programmes
- LeetCode: Search in Rotated Sorted Array II
- 使用 Return注意事项
- 第七周项目3差值求两数大小
- 利用JQUERY操作Radio
- java中对象类型转换
- UITabBarController 和 UINavigationController 的 popToRootViewController
- SAE数据库完美备份加强版
- MAC工具
- 文本比较算法剖析(1)-如何确定最大匹配率