码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode:Search in Rotated Sorted Array

时间:2015-03-09 18:57:19      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

题目要求:

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.

题目地址:https://leetcode.com/problems/search-in-rotated-sorted-array/

 

public class Solution {
    public static int search(int[] A, int target) {
            int first=0,last=A.length-1,mid;
            while(first<=last){
                mid=(first+last)/2;
                System.out.println("当前搜索范围"+A[first]+"--"+A[last]+",mid="+A[mid]);
                if(A[mid]==target)return mid;
                else if(A[first]<=A[mid]){//左有序
                    
                    if(target<A[first]||target>A[mid]){
                        
                        first=mid+1;
                    }else{
                        last=mid-1;
                    }
                }else{//右有序
                    if(target<A[mid]||target>A[last]){
                        last=mid-1;
                    }else{
                        first=mid+1;
                    }
                    
                }
            }
            return -1;
        }
}

POINTS:和传统2分查找无差别,只是通过A[mid]与A[first]A[last]的大小比较确定翻转的奇异点在2段范围中的哪一段,在对正常有序的那一段判断下目标在不在其中。

leetcode:Search in Rotated Sorted Array

标签:

原文地址:http://www.cnblogs.com/charlesdoit/p/4324148.html

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