Saturday, November 21, 2015

[leetcode] Search in rotated sorted array

唉。。想太复杂了,,其实就是看看那边sort掉的..然后判断target在不在那边,不在就扔到另一边继续找
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Solution {
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length-1;
        while (left <= right){
            int mid = (left+right)/2;
            if (nums[mid] == target) return mid;
            if (nums[mid] < nums[right]){
                if(target > nums[mid] && target <= nums[right]){
                    left = mid + 1;
                }else{
                    right = mid-1;
                }
            }else{
                if (target < nums[mid] && target >= nums[left]){
                    right = mid-1;
                }else{
                    left = mid+1;
                }
            }
        }
        return -1;
    }
}

No comments:

Post a Comment