LeetCode33. 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.


思路

首先要觀察這個數組的特點,即這個數組的分佈是分兩段的曾序列,滿足這樣的特點——{mid,...max,min,...submid},這裏我用submid來表示次中等大的元素。

那麼我們首先拿target跟首元素比較,也就是mid;如果target > mid , 那麼我們從頭開始尋找;如果target < mid,那麼我們從尾端開始倒着尋找(這樣可以提高平均效率);由於題目說明沒有重複,那麼找的次數最多也就是 |target - mid| ,如果還沒找到,那就意味着不在數組裏頭了;

最後注意下標不要越界即可。


代碼

public class Solution {
    public int search(int[] nums, int target) {
        int length = nums.length;
        if(length < 1)  return -1;
        if(target == nums[0])   return 0;
        int cha = target - nums[0];
        if(cha > 0){
            for(int i = 1 ; i <= cha && i < length; ++ i){
                if(nums[i] == target)  return i;
                if(nums[i] - nums[i-1] < 0) return -1;
            }
            return -1;
        }
        else{
            int j = length - 1;
            if(nums[j] == target) return j;
            -- j;
            for( ; j >= j + cha && j >= 0 ; -- j){
                if(nums[j] == target)  return j;
                if(nums[j] > nums[j + 1])   return -1;
            }
            return -1;
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章