Leetcode33. Search in Rotated Sorted Array

Posted 于淼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode33. Search in Rotated Sorted Array相关的知识,希望对你有一定的参考价值。

Question:

Suppose an array sorted in ascending order 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.

You may assume no duplicate exists in the array.

Tips:

给定一个数组,该数组是由一个有序的数组经过旋转(即将前面一段数字接到整个数组之后)得到的。判断target是否存在于该数组之中。

数组中不存在重复数字,如果target存在,返回他的index不存在则返回-1.

思路:

查找某数字是否存在,可以使用二分查找,但是由于该数组不是正常的有序,不能使用正常的BS。

设置两个指针,low high分别指向数组的首尾,mid=(high+low)/2;旋转后的数组用mid分为俩半,必然有一半是有序的,先判断target是不是在有序的一半内,如果在直接进行二分搜索,如果不在那么就在另外一部分里面。

代码:

public int search(int[] nums, int target) {
        if (nums == null || nums.length == 0)
            return -1;
        int len = nums.length ;
        int low = 0;
        int high = len - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (nums[mid] == target) 
                return mid;
            if (nums[low] <= nums[mid]) {
                if(target<nums[mid] && target>=nums[low]){
                    high=mid-1;
                }else{
                    low=mid+1;
                }
                
            }else{
                if(target>nums[mid] && target<=nums[high]){
                    low=mid+1;
                }else
                    high=mid-1;
            }

        }
        return -1;
    }

 

以上是关于Leetcode33. Search in Rotated Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 33. Search in Rotated Sorted Array

leetcode33. Search in rotated sorted array

一天一道LeetCode#33. Search in Rotated Sorted Array

leetcode 33. Search in Rotated Sorted Array

Leetcode33. Search in Rotated Sorted Array

LeetCode题意分析&解答33. Search in Rotated Sorted Array