首页 > 程序开发 > 软件开发 > 其他 >

LeetCode 33 Search in Rotated Sorted Array (二分查找 推荐)

2016-09-08

LeetCode 33 Search in Rotated Sorted Array (二分查找 推荐)

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

题目分析:这题目是我微软探星夏令营二面的第二题,一开始给的最简单的思路就是先用一次二分找拐点,然后再对某一边二分,面试官问能不能不找拐点,想了下,没问题,其实二分过程中就能判断出拐点了,每次二分后比较nums[left] 和nums[mid]的值,如果nums[left]

public class Solution {
    public int search(int[] nums, int target) {
        int r = nums.length - 1;
        int l = 0, mid;
        while (l <= r) {
            mid = (l + r) >> 1;
            if (nums[mid] == target) {
                return mid;
            }
            if (nums[l] <= nums[mid]) {
                if (nums[l] <= target && target < nums[mid]) {
                    r = mid - 1;
                }
                else {
                    l = mid + 1;
                }
            }
            else {
                if (nums[mid] < target && nums[r] >= target) {
                    l = mid + 1;
                }
                else {
                    r = mid - 1;
                }
            }
        }
        return -1;
    }
}
相关文章
最新文章
热点推荐