LeetCode: https://oj.leetcode.com/problems/search-in-rotated-sorted-array/
该问题要在一个旋转的排序数组里面寻找目标值,对于排好序的数组的查找问题,一般会想到二分法,而该问题属于分段有序,所以也可以采用二分查找的方法;关键在于如何对数组的分类进行考虑;很显然,对于二分后子数组,有两种情况:1. 完全递增 2. 分层两段递增数组;第一种情况很好考虑,第二种情况要对他再进行二分,又要考虑两种情况:1. 二分点在第一段递增子数组中,还是在第二段递增子数组中。
代码如下:
public class Solution {
public int search(int[] A, int target) {
if(A == null || A.length == 0)
return -1;
int l = 0;
int r = A.length-1;
while(l <= r){
int m = (l+r)/2;
if(A[m] == target)
return m;
if(A[l] <= A[r]){
if(A[m] < target){
l = m+1;
}else{
r = m-1;
}
}else{
if(A[m] >= A[l]){
if(target >= A[l] && target < A[m])
r = m-1;
else
l = m+1;
}
else{
if(target >= A[l] || target < A[m])
r = m-1;
else
l = m+1;
}
}
}
return -1;
}
}
LeetCode: https://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/
对于具有重复元素的数组,当收尾的数据相同时,由于不能确定数组的情况以及数据所在的子数组,所以采用最naive的方法(遍历):
public class Solution {
public boolean search(int[] a, int target) {
for(int i = 0; i < a.length; i++){
if(a[i] == target)
return true;
}
return false;
}
}