当前位置: 首页 > news >正文

在排序数组中查找元素的第一个和最后一个位置

题目描述

给你一个按照非递减顺序排列的整数数组nums,和一个目标值target。请你找出给定目标值在数组中的开始位置和结束位置。

如果数组中不存在目标值target,返回[-1, -1]

你必须设计并实现时间复杂度为O(log n)的算法解决此问题。

解题思路:

class Solution { public int[] searchRange(int[] nums, int target) { int[] res = new int[]{-1,-1}; int left = 0; int right = nums.length-1; while(left <= right){ int temp = (left + right) >> 1; if(nums[temp] > target){ right = temp - 1; }else if(nums[temp] < target){ left = temp + 1; }else{ left = temp; right = temp; while((right <nums.length-1)&&(nums[right] == nums[right+1])){ right++; } while((left > 0)&&(nums[left] == nums[left-1])){ left--; } res[0] = left; res[1] = right; } } return res; } }

这是最朴素的思想,二分查找,如果找到了再往两边拓展,处理边界条件,只可惜超时了。

需要对二分法再进行二分查找。

官方题解:

class Solution { public int[] searchRange(int[] nums, int target) { int leftIdx = binarySearch(nums, target, true); int rightIdx = binarySearch(nums, target, false) - 1; if (leftIdx <= rightIdx && rightIdx < nums.length && nums[leftIdx] == target && nums[rightIdx] == target) { return new int[]{leftIdx, rightIdx}; } return new int[]{-1, -1}; } public int binarySearch(int[] nums, int target, boolean lower) { int left = 0, right = nums.length - 1, ans = nums.length; while (left <= right) { int mid = (left + right) / 2; if (nums[mid] > target || (lower && nums[mid] >= target)) { right = mid - 1; ans = mid; } else { left = mid + 1; } } return ans; } }
http://www.cnnetsun.cn/news/120337.html

相关文章:

  • Python大数据技术的基于Hadoop的健康饮食推荐系统的设计与实现_5578bn9k_yh025
  • 从文本到情感语音:EmotiVoice的技术实现路径
  • Kotaemon多租户支持能力曝光,适用于SaaS场景
  • EmotiVoice语音合成引擎的架构设计与原理剖析
  • 1、Linux API 与 Kylix 开发全解析
  • 3、深入探索Linux API:错误处理与特性对比
  • 17、深入理解Socket服务器的创建与应用
  • 18、Linux网络编程:socket API函数深度解析
  • 聚铭网络蝉联ISC.AI 2025创新百强,持续领跑安全运营、网络与流量安全双赛道
  • 29、Python 中进程与线程管理全解析
  • EmotiVoice开源模型本地部署避坑指南
  • 笔试强训day7
  • EmotiVoice情感编码技术揭秘:如何让AI说出喜怒哀乐?
  • 46、基于 Pthreads 的多线程编程:基础与同步解析
  • 48、基于 Pthreads 的多线程编程:同步机制深入解析
  • 52、基于 Pthreads 的多线程编程(三)
  • Kotaemon文档翻译功能扩展:跨语言问答不再是难题
  • 好无聊,最近没思路
  • Kotaemon水务管理系统智能预警机制
  • Kotaemon视频内容摘要生成实验记录
  • 用Matlab探索齿轮系统的奥秘:刚度计算与动力学响应
  • 【node阅读-0】下载编译node
  • EmotiVoice支持动态情感过渡,实现平滑情绪变化
  • EmotiVoice推理时显存占用优化方案(适用于低配GPU)
  • EmotiVoice支持HTTPS加密传输,保障数据安全
  • 2025年最新AI编程助手深度横评:按功能类型选对你的“副驾”
  • - - - 正则表达式匹配 diff - - -
  • Kotaemon支持PDF/PPT/Word等多种文档解析
  • Kotaemon在制造业知识管理中的创新应用案例
  • Kotaemon配置文件全参数说明,新手必看!