您的位置:首页 > 编程语言 > C语言/C++

【LeetCode刷题】旋转数组的查找 Search in Rotated Sorted Array

2014-10-06 13:30 591 查看
原文:http://www.dy1280.com/thread-685-1-1.html 

描述
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。

分析
二分查找,此题要特别注意边界值。此题的边界比较多。
(1)mid的位置判定,mid可能在左边区域,也可能在右边区域,需求通过(A[mid]与A[first]大小关系进行判定)
(2)在判定边界时,要注意考虑大于,小于,等于三种情况,在写代码时,本题我开始忘记了一个等号,如代码中标红的地方。
(3)二分的思想是一步一步将区域缩小,并且要充分考虑缩小的正确性,不能放松对边界的警惕(即要注意等于的情况)。

C++版代码

 

<span style="font-family:Microsoft YaHei;font-size:18px;">// 时间复杂度O(log n),空间复杂度O(1)
class Solution {
public:
int search(int A[], int n, int target) {
int first = 0, last = n;
while (first != last) {
const int mid = (first + last) / 2;
if (A[mid] == target)
return mid;
if (A[first] <= A[mid]) {
if (A[first] <= target && target < A[mid])
last = mid;
else
first = mid + 1;
} else {
if (A[mid] < target && target <= A[last-1])
first = mid + 1;
else
last = mid;
}
}
return -1;
}
};</span>


JAVA版

<span style="font-family:Microsoft YaHei;font-size:18px;">public int search(int[] A, int target) {
if(A==null||A.length==0)
return -1;
int first=0,last=A.length-1;
while(first<=last){
int mid=(first+last)/2;
if(A[mid]==target){
return mid;
}else if(A[mid]>=A[first]){
if(target>=A[first]&&target<A[mid]){
last=mid-1;
}else{
first=mid+1;
}
}else{
if(target>A[mid]&&target<=A[last]){
first=mid+1;
}else{
last=mid-1;
}
}
}
return -1;
}
</span>


 

转载请注明出处!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐