标签:
题目要求:
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