`

Search for a Range

阅读更多
Given a sorted array of integers, find the starting and ending position of a given target value.

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

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

这道题目同样采用二分法,当找到目标元素后,因为存在重复元素,我们要从当前元素向两边扩散,然后得到一个范围。如何记录呢,我们可以new一个包含两个元素的数组result,当找到目标元素时,记录当前元素的下标m,让result[0] = m, result[1] = m, 然后以m为中心,向两边比较,左边相等的就让result[0]减1,右边相等的就让result[1]加1。最终得到了包含目标元素的范围。代码如下:
public class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] result = new int[2];
        result[0] = -1;
        result[1] = -1;
        if(nums == null || target < nums[0] || target > nums[nums.length - 1])
            return result;
        int l = 0;
        int r = nums.length - 1;
        while(l <= r) {
            int m = l + (r - l) / 2;
            if(nums[m] == target) {
                result[0] = m;
                result[1] = m;
                while(result[0] > 0 && nums[result[0] - 1] == target) 
                    result[0] --;
                while(result[1] < nums.length - 1 && nums[result[1] + 1] == target) 
                    result[1] ++;
                return result;
            } else if(nums[m] > target) {
                r = m - 1;
            } else {
                l = m + 1;
            }
        }
        return result;
    }
}
分享到:
评论

相关推荐

    A Route Search Method for Electric Vehicles in Consideration of Range

    ### 电动汽车路径搜索方法考虑续航能力 #### 概述 本文提出了一种针对电动汽车(Electric Vehicles, EVs)的新路径搜索方法,旨在帮助驾驶员在车辆剩余电量不足以到达目的地时找到包含充电站停留的最佳路线。...

    C语言-leetcode题解之34-search-for-a-range.c

    c语言入门 C语言_leetcode题解之34-search-for-a-range.c

    算法刷题笔记leetcode/lintcode

    - Search for a Range(搜索范围) - First Bad Version(第一个错误版本) - Search a 2D Matrix(二维矩阵中的搜索) - Search a 2D Matrix II(二维矩阵中的搜索II) - Find Peak Element(寻找峰值元素) ...

    Leetcode题目+解析+思路+答案.pdf

    - **Search for a Range**:在一个排序数组中查找目标值的第一个和最后一个位置。 - **Search Insert Position**:在排序数组中查找目标值的插入位置。 2. **位操作(Bit Manipulation)**: - **Missing Number...

    LeetCode练习答案

    - **搜索区间(Search for a Range)**: 在一个按升序排列的数组中查找目标值的起始和结束位置。 - **搜索插入位置(Search Insert Position)**: 在一个排序数组中找到特定目标值应该被插入的位置。 - **寻找峰值元素...

    lintcode算法分析和解答

    - **查找目标元素范围(Search for a Range)** - 查找目标元素在有序数组中的起始和结束位置。 - **第一个错误版本(First Bad Version)** - 在一系列版本中找到第一个错误版本。 - **二维矩阵查找(Search a 2D ...

    算法学习笔记

    - Search for a Range:在排序数组中搜索给定值的起始和结束位置。 - Find Peak Element:在一个整数数组中找到一个峰值元素。 - Median of Two Sorted Arrays:两个排序数组的中位数。 - Sqrt(x):计算并返回x的...

    算法-leetcode-剑指offer上的题很多

    - **在排序数组中寻找范围(Search for a Range)**: 在排序数组中找到给定数字范围的位置。 - **查找矩阵中的位置(Search a 2D Matrix)**: 在一个排序的矩阵中查找一个数字的位置。 #### 特殊算法 - **查找峰值元素...

    _leetcode-python.pdf

    - Search for a Range: 给定一个按照升序排列的数组,和一个目标值,确定该目标值在数组中的开始位置和结束位置。 - Search Insert Position: 在一个排序数组中查找一个目标值,如果不存在则返回应该插入的位置。 - ...

    paper: Generalized Search Trees for Database Systems

    In a single data structure, the GiST provides all the basic search tree logic required by a database system, thereby unifying disparate structures such as B+-trees and R-trees in a single piece of ...

    Leetcode代码以及解答(2)

    Search for a Range **知识点:** - **问题描述:** - 给定一个排序数组和一个目标值,在数组中查找目标值出现的第一个和最后一个位置。 - **解决方案分析:** - **二分查找:** - 分别查找目标值的第一个和...

    LeetCode C++全解

    1. Introduction 2. Array i. Remove Element ii. Remove Duplicates from Sorted Array iii....iv....v....vi....vii....viii....ix....x.... Search for a Range xiii. Search Insert Position xiv. Find Peak Element

    A Survey of Monte Carlo Tree Search Methods

    Monte Carlo Tree Search (MCTS) is a recently proposed search method that combines the precision of tree search with the generality of random sampling. It has received considerable interest due to its ...

    Elasticsearch.Essentials.1784391018.pdf

    Here's what you need―a highly practical guide that gives you a quick start with ElasticSearch using easy-to-follow examples; get up and running with ElasticSearch APIs in no time Get the latest ...

    自己动手写搜索引擎 第4章 光盘实例

    * Implementation of a Ternary Search Trie, a data structure for storing &lt;code&gt;String&lt;/code&gt; objects * that combines the compact size of a binary search tree with the speed of a digital search trie, ...

    Predicting Serial Killers’ Home Base Using a Decision Support System

    The optimal search cost was also found to be for a function that did not include any buffer zone. The optimal, average search cost across the whole sample was 11% of the defined search area. Fifty-...

    R for beginner

    R offers a wide range of functions and operators to manipulate objects. Some common operations include: - **Creating Objects**: Use assignment operators (`) to create new objects. - **Converting ...

Global site tag (gtag.js) - Google Analytics