【LeetCode】-Search in Rotated Sorted Array

来源:互联网 发布:千牛mac电脑官方下载 编辑:程序博客网 时间:2024/06/05 10:52

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.

public class Solution {    public int search(int[] A, int target) {        int index = -1;index = find( A, 0, A.length-1, target );return index;       }        private int find( int[] arr, int start, int end, int target ){if( start>end )return -1;//如果这部分是递增序列,进行二分查找int index = -1;if( arr[start]<arr[end] ){int left = start;int right = end;while( left<=right ){int mid = (left+right)>>1;if( target>arr[mid] ){left = mid+1;}else if( target<arr[mid] ){right = mid-1;}else{index = mid;break;}}}else{int mid = (start+end)>>1;if( arr[mid]==target ){return mid;}index = find( arr, start, mid-1, target );if( index==-1 ){index = find( arr, mid+1, end, target );}}return index;}}


0 0
原创粉丝点击