首页 > 代码库 > 33. Search in Rotated Sorted Array

33. Search in Rotated Sorted Array

一、题目

  1、描述

    技术分享

  2、题意

    在一个有序但可能经过左右移动的数组里求出目标数的下标!

 

二、解答

    1、思路:

      可以采用依次比较的方法

    2、优化:

      因为移动后,一定有一个数字是最大的且该数将数组分成左右两边,左边的每一个数都比右边大,或者右边的数都比左边大!所以可以找出中间数,然后采用两次二分查找即可!

  

public class Solution {
    public int search(int[] nums, int target) {
        int low = 0;
        int len = nums.length;
        int high = len - 1;
        
        if(nums == null || len == 0)
            return -1;
            
        // find the biggest num index:  low
        while(low < high) {
            int median = (low + high) / 2;
            
            if(nums[median] > nums[low]) 
                low = median;
            else if(nums[median] < nums[low]){
                high = median - 1;
            } else {
                // median = low
                if(nums[low] <nums[high])
                    low = high;
                break;
            }
        }
        
        int index = binarySearch(nums, target, 0, low);
        if(index != -1)
            return index;
        
        index = binarySearch(nums, target, low + 1, len - 1);
        if(index != -1)
            return index;
        
        return -1;
    }

    private  int binarySearch(int[] nums, int target, int low, int high) {
        // 二分
        int median = (high+low) / 2;
        while(low <= high) {
            
            if(nums[median] == target) 
                return median;
            
            if(nums[median] > target) {
                high = median - 1;
            }
            else {
                low = median + 1;
            }
            median = low + (high-low) / 2;
        }
        return -1;
    }
}

 

三、总结

  二分查找比较简单,但是找分界数的时候,想了好久,可以画个图看一下!

  

33. Search in Rotated Sorted Array