Search in Rotated Sorted Array

来源:互联网 发布:侠盗猎车手5mac版 编辑:程序博客网 时间:2024/05/16 09:07

题目原型:

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.

基本思路:

题目大概意思就是在一个有序数组经过旋转后得到的数组中查找某个数,存在则返回此数的位置,不存在就返回-1。

首先我们要找到分界点,如:4,5,6,7,0,1,2的分界点就是7,然后再确定target在哪一个小数组中(4,5,6,7)还是(0,1,2),确定后利用二分搜索法搜索即可。

public int search(int[] A, int target){int low,high;//搜索旋转位置int rotatePoint = -1;int index = -1;for(int i = 0;i<A.length-1;i++){ if(A[i]>A[i+1]) { rotatePoint = i; break; }}if(rotatePoint==-1){index = searchByBin(A, 0, A.length-1, target);}else{if(target>A[rotatePoint])return -1;else if(target<A[rotatePoint]){if(target>A[0]){low = 0;high = rotatePoint-1;index = searchByBin(A, low, high, target);}else if(target<A[0]){low = rotatePoint+1;high = A.length-1;index = searchByBin(A, low, high, target);}elseindex = 0;}elseindex = rotatePoint;}return index;}// 二分查找public int searchByBin(int[] A, int low, int high, int target){if (low > high)return -1;int mid = (low + high) / 2;if (target == A[mid])return mid;else if (target > A[mid])return searchByBin(A, mid + 1, high, target);elsereturn searchByBin(A, low, mid - 1, target);}


0 0
原创粉丝点击