[LeetCode 033] Search in Rotated Sorted Array

Search in Rotated Sorted Array

[LeetCode 033] Search in Rotated Sorted Array_第1张图片

Implementation

public class Solution {
    public int search(int[] nums, int target) {
        int start = 0;
        int end = nums.length - 1;
        while (start <= end) {
            int mid = start + (end - start) / 2;
            if (nums[mid] == target)
                return mid;
            if (nums[mid] >= nums[start]) {
                if (target > nums[mid] || target < nums[start])
                    start = mid + 1;
                else
                    end = mid - 1;
            }
            else {
                if (target > nums[mid] && target < nums[start])
                    start = mid + 1;
                else
                    end = mid - 1;
            }
        }
        return -1;
    }
}

你可能感兴趣的:([LeetCode 033] Search in Rotated Sorted Array)