【LeetCode】Search in Rotated Sorted Array II 解题报告
来源:互联网 发布:淘宝号几单有一心 编辑:程序博客网 时间:2024/06/08 13:14
【题目】
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,在递归时需要先去重,再迭代(递归)。
【C++代码】
class Solution {public: bool search(int A[], int n, int key) { if (n<=0) return false; if (n==1){ return (A[0]==key) ? true : false; } int low=0, high=n-1; while( low<=high ){ if (A[low] < A[high] && ( key < A[low] || key > A[high]) ) { return false; } //if dupilicates, them binary search the duplication while (low < high && A[low]==A[high]){ low++; } int mid = low + (high-low)/2; if (A[mid] == key) return true; //the target in non-rotated array if (A[low] < A[mid] && key >= A[low] && key< A[mid]){ high = mid - 1; continue; } //the target in non-rotated array if (A[mid] < A[high] && key > A[mid] && key <= A[high] ){ low = mid + 1; continue; } //the target in rotated array if (A[low] > A[mid] ){ high = mid - 1; continue; } //the target in rotated array if (A[mid] > A[high] ){ low = mid + 1; continue; } //reach here means nothing found. low++; } return false; }};
【简洁Java版】
public class Solution { public boolean search(int[] A, int target) { int l = 0; int r = A.length - 1; while (l <= r) { while (l < r && A[l] == A[r]) l++; int mid = (l + r) / 2; if (target == A[mid]) return true; if (A[l] <= A[r]) { if (target < A[mid]) r = mid - 1; else l = mid + 1; } else if (A[l] <= A[mid]) { if (target < A[l] || target > A[mid]) l = mid + 1; else r = mid - 1; } else { if (target < A[mid] || target > A[r]) r = mid - 1; else l = mid + 1; } } return false; }}
0 0
- 【LeetCode】Search in Rotated Sorted Array II 解题报告
- [leetcode] 81. Search in Rotated Sorted Array II 解题报告
- [LeetCode] Search in Rotated Sorted Array II 解题报告
- [Leetcode] 81. Search in Rotated Sorted Array II 解题报告
- Leetcode 81. Search in Rotated Sorted Array II 旋转数组查询2 解题报告
- 【LeetCode】Search in Rotated Sorted Array 解题报告
- [leetcode] 33. Search in Rotated Sorted Array 解题报告
- [LeetCode] Search in Rotated Sorted Array 解题报告
- LeetCode(33) Search in Rotated Sorted Array解题报告
- [Leetcode] 33. Search in Rotated Sorted Array 解题报告
- Search in Rotated Sorted Array LeetCode解题报告
- Search in Rotated Sorted Array解题报告
- Search in Rotated Sorted Array解题报告
- 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
- React Native使用初探 --------- OpenGL应用
- android中invalidate()的自动清屏含义以及屏幕刷新
- NOJ 网络赛 L题 送花
- 1.9
- maven开发环境的配置
- 【LeetCode】Search in Rotated Sorted Array II 解题报告
- Android NDK开发(一)环境搭建及运行示例
- 游戏中的随机间隔
- 【深入浅出IOS开发】UITabBarController和UINavigationController混合使用
- linux main.c中的初始化
- JavaScript之正则表达式
- 简单工厂模式
- Netstat
- leetcode_num155_Min Stack