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答案,思路相同,可以了。

浙公网安备 33010602011771号