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

题目链接: https://leetcode.com/problems/search-in-rotated-sorted-array/

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TomLazy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值