当前位置:网站首页>【LeetCode-34】在排序数组中查找元素的第一个和最后一个位置
【LeetCode-34】在排序数组中查找元素的第一个和最后一个位置
2022-08-11 05:30:00 【Ring*】
10.4 在排序数组中查找元素的第一个和最后一个位置【34】
10.4.1 题目描述
给你一个按照非递减顺序排列的整数数组 nums,和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target,返回 [-1, -1]。
你必须设计并实现时间复杂度为 O(log n) 的算法解决此问题。
10.4.2 方法一:二分查找
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;
}
}
复杂度分析
- 时间复杂度: O(logn) ,其中 nn 为数组的长度。二分查找的时间复杂度为 O(logn),一共会执行两次,因此总时间复杂度为 O(logn)。
- 空间复杂度:O(1) 。只需要常数空间存放若干变量。
10.4.3 my answer—二分查找
class Solution {
public int[] searchRange(int[] nums, int target) {
int left = 0;
int right = nums.length -1 ;
int ans = -1;
while(left <= right){
int mid = left + (right - left)/2;
if(nums[mid]>target){
right = mid - 1;
}else if(nums[mid]<target){
left = mid + 1;
}else{
ans = mid;
break;
}
}
if(ans==-1)return new int[]{
-1,-1};
int ans_left = ans;
int ans_right = ans;
while(true){
ans_left--;
if(ans_left<0 || nums[ans_left] != target){
break;
}
}
while(true){
ans_right++;
if(ans_right>nums.length-1 || nums[ans_right] != target){
break;
}
}
return new int[]{
ans_left+1,ans_right-1};
}
}
边栏推荐
猜你喜欢
星盟-pwn-babyfmt
基于微信小程序云开发实现的电商项目,可以自行定制开发
OpenMLDB: Consistent production-level feature computing platform online and offline
活动预告 | 4月23日,多场OpenMLDB精彩分享来袭,不负周末好时光
buuctf hacknote
IO流和序列化与反序列化
自己动手写RISC-V的C编译器-01实现加减法
Day 78
JS advanced web page special effects (pink teacher notes)
场景驱动的特征计算方式OpenMLDB,高效实现“现算先用”
随机推荐
自己动手写RISC-V的C编译器-00环境配置
Jetpack's dataBinding
mk文件介绍
贡献者任务第三期精彩来袭
127.0.0.1 connection refused
C-自定义类型(结构体、枚举、联合)
8-byte standard request parsing during USB enumeration
C语言-7月31日-指针的总结以及typedef关键字
Some formulas for system performance and concurrency
C语言-7月21日-指针的深入
第六届蓝帽杯 EscapeShellcode
JS case exercise (classic case of teacher pink)
虚拟机更改IP地址
Pinyougou project combat notes
Tinker接入全流程---编译篇
mongoose连接mongodb不错,显示encoding没有定义
基于微信小程序云开发实现的电商项目,可以自行定制开发
three.js基础学习
Use c language to implement tic-tac-toe chess (with source code, you can run it directly)
OpenMLDB官网升级,神秘贡献者地图带你快速进阶