栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【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

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)的算法。

【测试用例】:

【约束】:

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/863497.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号