【LeetCode】No.33. Search in Rotated Sorted Array -- Java Version

194 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第16天。

题目链接: leetcode.com/problems/se…

1. 题目介绍

There is an integer array nums sorted in ascending order (with distinct values).

【Translate】: 有一个按升序(具有不同的值)排序的整数数组nums。

Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].

【Translate】: 在传递给你的函数之前,nums可能是在未知的枢轴索引k(1 <= k <nums.length)上旋转的,因此结果数组为[nums [k],nums [k+1],...,nums [n-1],nums [0],nums [1],...,nums [k-1]](0-索引)。例如,[0,1,2,4,5,6,7]可以在枢轴索引3处旋转,变成[4,5,6,7,0,1,2]。

Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

【Translate】: 给定可能的旋转后的数组nums和一个整数目标,如果target在nums中,则返回其索引,如果不在nums中,则返回-1。

You must write an algorithm with O(log n) runtime complexity.

【Translate】: 你必须写一个运行复杂度为O(log n)的算法。

【测试用例】: test 【约束】: Constraints

2. 题解

2.1 暴力穷举 -- O(n)

  这一题很简单,但是难点在于如何以O(log n)来实现。

    public int search(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++)
        {
            if (nums[i] == target) return i;
        }
        return -1;
    }

case

2.2 Binary Search -- O(log n)

  nagthane所提供的题解 0ms 100% faster O(log(n)) binary search easy with explaination in comments,和jerry13466所提出的Revised Binary Search几乎一致。

 public int search(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        int l = 0;
        int r = nums.length - 1;
        while(l<r){
            int mid = (l+r)/2;
            if(nums[mid] == target)
                return mid;
            if(nums[l] <= nums[mid]){ //checking if first half array is sorted if so
                if(nums[l] <= target && target < nums[mid]){ //check if target lies in the range if so
                    r = mid - 1;                              // search in first half only
                }else                                         //else search in second half
                    l = mid + 1;
            }else{  //if first half isn't sorted go and check for second
                if(nums[mid] < target && target <= nums[r]){ //check if target lies in second half
                    l = mid + 1;                             //if so search in second half
                }else{
                    r = mid - 1;
                }
            }
        }
        return nums[l] == target ? l : -1;
    }

case2