leetcode 33. Search in Rotated Sorted Array

Posted jamieliu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 33. 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.

Your algorithm‘s runtime complexity must be in the order of O(log n).

Example 1:

Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4

Example 2:

Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1

 

解法一:我的解法 指针移动查找 但是可能不符合O(logN)

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

 

解法二:binary search

public int search(int[] A, int target) {
    int lo = 0;
    int hi = A.length - 1;
    while (lo < hi) {
        int mid = (lo + hi) / 2;
        if (A[mid] == target) return mid;
        
        if (A[lo] <= A[mid]) {
            if (target >= A[lo] && target < A[mid]) {
                hi = mid - 1;
            } else {
                lo = mid + 1;
            }
        } else {
            if (target > A[mid] && target <= A[hi]) {
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }
    }
    return A[lo] == target ? lo : -1;
}

 

以上是关于leetcode 33. Search in Rotated Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 33. Search in Rotated Sorted Array

leetcode33. Search in rotated sorted array

一天一道LeetCode#33. Search in Rotated Sorted Array

leetcode 33. Search in Rotated Sorted Array

Leetcode33. Search in Rotated Sorted Array

LeetCode题意分析&解答33. Search in Rotated Sorted Array