首页 > 代码库 > Search in Rotated Sorted Array I && II
Search in Rotated Sorted Array I && II
对翻过一次的排序数组二分查找,要利用好已排序这个条件
class Solution { public: int search(int A[], int n, int target) { int left = 0, right = n-1; while(left <= right){ int mid = (left+right)/2; if(A[mid] == target) return mid; if(A[left] <= A[mid]){ if(A[left] <= target && target < A[mid]) right = mid-1; else left = mid+1; } else { if(A[mid] < target && target <= A[right]) left = mid+1; else right = mid-1; } } return -1; } };
II中允许重复数字,碰到相等的向前移。
class Solution { public: bool search(int A[], int n, int target) { int left = 0, right = n-1; while(left <= right){ int mid = (left+right)/2; if(A[mid] == target) return true; if(A[left] < A[mid]){ if(A[left] <= target && target < A[mid]) right = mid-1; else left = mid+1; } else if(A[left] > A[mid]){ if(A[mid] < target && target <= A[right]) left = mid+1; else right = mid-1; } else left++; } return false; } };
Search in Rotated Sorted Array I && II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。