博客
关于我
【LeetCode(Java) - 34】在排序数组中查找元素的第一个和最后一个位置
阅读量:57 次
发布时间:2019-02-25

本文共 1370 字,大约阅读时间需要 4 分钟。

文章目录

1、题目描述

在这里插入图片描述

2、解题思路

  定义一个方法,该方法的功能是找出 target 在 nums 数组中的开始位置或者结束位置,该方法有一个参数 left,该参数为 true 时返回的时开始位置,false 时返回的是结束位置。

  因为题目不保证 nums 数组一定存在 target,因此搜索区间为左开右闭,即初始时:左边界 lo = 0;右边界 hi = nums.length。

  查找开始位置时:

  1、如果 nums[mid] 大于 target,不用说,直接更新右边界为 mid;

  2、当 nums[mid] == target 时,因为 nums[mid] 可能就是开始位置,于是更新右边界为 mid;

  3、当结束 while 循环时,此时 lo == hi,因此直接返回 lo 即可。

  查找结束位置时:

  1、如果 nums[mid] 大于 target,同样直接更新右边界为 mid;

  2、如果 nums[mid] 等于 target,nums[mid] 同样有可能就是结束位置,于是更新左边界为 mid + 1;

  在求结束位置时,返回的值是右边界的下一位,因此要进行减一操作。

  也可以把求开始位置和结束位置拆开成两个方法,更为直观。

3、解题代码

class Solution {       private int extremeInsertionIndex(int[] nums, int target, boolean left) {           int lo = 0;        int hi = nums.length;        while (lo < hi) {               int mid = lo + (hi - lo) / 2;            if (nums[mid] > target || (left && target == nums[mid])) {                   hi = mid;            } else {                   lo = mid + 1;            }        }        return lo;    }    public int[] searchRange(int[] nums, int target) {           int[] targetRange = {   -1, -1};        int leftIdx = extremeInsertionIndex(nums, target, true);        if (leftIdx == nums.length || nums[leftIdx] != target) {               return targetRange;        }        targetRange[0] = leftIdx;        targetRange[1] = extremeInsertionIndex(nums, target, false) - 1;        return targetRange;    }}

转载地址:http://mwq.baihongyu.com/

你可能感兴趣的文章
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>