Leetcode33. Search in Rotated Sorted Array

关键词:二分查找

看到O(logn)就想到了二分查找,但是怎么实施呢?并没想到,于是看了discuss。

https://leetcode.com/problems/search-in-rotated-sorted-array/discuss/14472/Java-AC-Solution-using-once-binary-search

很巧妙的适应版二分查找。

class Solution {
    public int search(int[] nums, int target) {
        int l=0,r=nums.length-1;
        while(l<=r){
            int m=(l+r)/2;
            if(target==nums[m]) return m;
            if(nums[m]>=nums[l]){   //left part is still in ascending order without rotation,then right part is definitely rotated
                if(target<nums[m]&&target>=nums[l])  //judge if target is in the order part
                    r=m-1;
                else
                    l=m+1;
            }
            else{   //same as if(nums[m]<=nums[r]) means the right part is in ascending order and left part is rotated
                if(target>nums[m]&&target<=nums[r]) //judge if target is in the order part
                    l=m+1;
                else
                    r=m-1;
            }
        }
        return -1;
    }
}

5-10ms ,100%-23%.

看了别的5ms答案,思路相同,可以了。

posted @ 2018-12-26 17:00  大胖子球花  阅读(93)  评论(0)    收藏  举报