您的位置:首页 > 编程语言 > PHP开发

FTPrep, 81 Search in Rotated Sorted Array II

2017-09-20 13:55 387 查看
经典老题,是二分法的变形题目,TODO: 把这道题和search in 2D 这个二分法的题目放在一起总结,他自身也是跟没有duplicates的 rotated sorted array 是相联系的。

代码:

class Solution {
public boolean search(int[] nums, int target) {
if(nums.length==0) return false;
int left=0, right=nums.length-1;
while(left<=right){
int mid= left+(right-left)/2;
if(target==nums[mid]) return true;
if(nums[mid]>nums[left]){ // by comparing the two ends of the left side
// we know that left side is still sorted, so left side is the good place for setting the checking condition
if(nums[left]<=target && target<nums[mid]) right=mid-1;
else left=mid+1;
}
else if(nums[mid]<nums[left]){ // this makes much sense, always checking the exclusive condition
// which is more logically obvious stuff!! bug I made: nums[mid]<nums[righ]
if(nums[mid]<target && target<=nums[right]) left = mid+1;
else right=mid-1;
}
else{ // this is for the variant of question only, for the duplicate ones.
left++; // cannot be right--, since the checking condition is nums[left]==nums[mid], explicitly
}
}
return false;
}
}

// 关于复杂度的分析要看看ganker的博客,特例:整个array 全是相同的数 111111 那么就要把left 从头数到尾巴,那就是O(N)

结构和一般的二分法类似,但是在while内部,要通过判断左边(或者右边,但是如果选择了一边就一直沿用,保持consistent )是否是order的,那么很简单的就是判断左半边的两头是不是有 left<mid,如果这样的,那就判断target是不是在这边,是的话,就更新right,不是就更新left。第二种情况,如果 left>mid,那么就是说右边是order的,相应的看target是否在右边,如果yes,更新left,否则更新right。最后因为有duplicates的出现,那就是有 mid==left的情况,这时,就相应的把left++,因为是左边有重复。这里的话一定要保持
consistent,一开始是比较左边的,那就保持判断的条件一直是left。left是duplicates的话,也是要向右移动left
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: