标签:leetcode
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://oj.leetcode.com/problems/search-in-rotated-sorted-array/题目:假设一个有序数组在某一点上被折叠,你不知道哪一点上。
给定一个数组和一个目标值,找出目标值在数组中的索引。
思路:可以用线性查找的方法,但是就背离了题目中的有序这个条件。比较好的办法是二分查找,但是需要找到有序的一部分,才可以使用二分。
public int search(int[] A, int target) {
int low = 0, high = A.length - 1;
while (low <= high) {
int mid = (high + low) / 2;
if (target == A[mid])
return mid;
if (A[mid] > A[low]) {
if (target >= A[low] && target < A[mid])
high = mid - 1;
else
low = mid + 1;
} else if(A[mid] < A[low]){
if (target <= A[high] && target > A[mid])
low = mid + 1;
else
high = mid - 1;
}else
low += 1;
}
return -1;
}
LeetCode——Search in Rotated Sorted Array,布布扣,bubuko.com
LeetCode——Search in Rotated Sorted Array
标签:leetcode
原文地址:http://blog.csdn.net/laozhaokun/article/details/38141433