码迷,mamicode.com
首页 > 编程语言 > 详细

leetCode 33.Search in Rotated Sorted Array(排序旋转数组的查找) 解题思路和方法

时间:2015-07-08 18:55:29      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:leetcode   二分查找   search   

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.

You may assume no duplicate exists in the array.


思路:此题算法上不难,第一步计算旋转的步长。然后根据步长分情况得到升序的新的数组。然后二分查找target的索引,找到后再分情况返回元素的位置。

具体代码如下:

public class Solution {
    public int search(int[] nums, int target) {
        if(nums.length == 0){
            return -1;
        }
        
        if(nums.length == 1){
            if(nums[0] == target)
                return 0;
            return -1;
        }
        
        int rotate = 0;//旋转的步长
        for(int i = nums.length - 1; i > 0; i--){
            if(nums[i] < nums[i-1]){
                rotate = i;
                break;
            }
        }
        int[] a = new int[nums.length];
        //将数组按升序填充到新数组
        for(int i = rotate; i < nums.length; i++){
            a[i - rotate] = nums[i];//后面未旋转部分
        }
        for(int i = 0; i < rotate; i++){
            a[i+nums.length-rotate] = nums[i];//前面旋转部分
        }
        
        int index = -1;
        //二分查找
        int low = 0;
        int hight = nums.length - 1;
        while(low <= hight){
            int mid = (low + hight)/2;
            if(a[mid] > target){
                hight = mid - 1;
            }else if(a[mid] == target){
                index = mid;
                break;
            }else{
                low = mid + 1;
            }
        }
        if(index == -1)
            return -1;
        if(index + rotate > nums.length - 1)
            return index + rotate - nums.length;
        return index + rotate;
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

leetCode 33.Search in Rotated Sorted Array(排序旋转数组的查找) 解题思路和方法

标签:leetcode   二分查找   search   

原文地址:http://blog.csdn.net/xygy8860/article/details/46806349

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!