1. 程式人生 > >字串演算法——旋轉陣列中查詢目標值(Search in Rotated Sorted Array)

字串演算法——旋轉陣列中查詢目標值(Search in Rotated Sorted Array)

問題:
Suppose an array sorted in ascending order 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.
解決思路

:如果不考慮複雜度,可以對陣列每個元素進行比較,看是否存在查詢的目標值,如果考慮複雜度,可以利用陣列原來有序的先驗知識,必然陣列一邊是有序的,一邊是無序的,使用二分查詢的方法。

class Solution {
    public int search(int[] nums, int target) {
        int len = nums.length;
        if(len==0)return -1;
        return dfs(nums,target,0,len-1);


    }
    private int dfs(int []nums,int target,int
min,int max){ if(min>max){ return -1; } int mid = (min+max)/2;//中間索引 if(nums[mid] ==target)return mid; if(nums[mid]>nums[min]){//中間索引左側是有序的 if(nums[mid]>target && nums[min]<target){//落在索引左側 return dfs(nums,target,min
+1,mid-1); } if(nums[min] == target){ return min; } return dfs(nums,target,mid+1,max);//落在索引右側 }else {//索引右側是有序的 if(nums[mid]<target && nums[max]>target){//落在索引右側 return dfs(nums,target,mid+1,max-1); } if(nums[max] ==target){ return max; } return dfs(nums,target,min,mid-1);//落在索引左側 } } }