LeetCode33. Search in Rotated Sorted Array

来源:互联网 发布:yum预付卡章程 编辑:程序博客网 时间:2024/06/07 03:37

题目

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;        }    }}


原创粉丝点击