博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【LeetCode】【找元素】Find First and Last Position of Element in Sorted Array
阅读量:4462 次
发布时间:2019-06-08

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

描述:

Given an array of integers nums sorted in ascending order, 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].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6Output: [-1,-1]

 

思路一:一次Binary Search

先使用二分查找找到和taget相等的起始位置的元素,然后在这个位置向两边扩散找到值相同的范围。

class Solution {public:    vector
searchRange(vector
& nums, int target) { vector
res(2,-1); if(nums.size() == 0) return res; int cau = dichotomy(nums,target); if(cau == -1) return res; else{ int i = cau,j = cau; cout<
<
=0 && nums[i] == target) || (j<=nums.size()-1 && nums[j] == target)){ if(i>=0 && nums[i] == target){ res[0] = i; cout<
<
& nums, int target){ int low = 0,int high = nums.size() - 1; while(low < high){ int mid = (low + high + 1) / 2; if(nums[mid] == target) return mid; if(nums[mid] < target) low = mid + 1; else high = mid - 1; } return -1; }};

 

思路二:两3次Binary Search

先根据上述的二分查找,找到起始位置的元素,然后从low开始继续使用一次二分查找找到target+1的位置,然后返回这个位置it - 1,从而找到起始和终止的范围。

class Solution {public:    vector
searchRange(vector
& nums, int target) { vector
res(2,-1); if(nums.size() == 0) return res; int low = dichotomy(nums,target,0); //找起始元素 cout<
<
& nums, int target, int low){ int high = nums.size(); //核心 while(low < high){ int mid = (low + high ) / 2; if(nums[mid] < target) low = mid + 1; else high = mid; } return low; }};

 

转载于:https://www.cnblogs.com/ygh1229/p/9726966.html

你可能感兴趣的文章
使用 WordPress 的导航菜单
查看>>
input只能输入数字和小数点,并且只能保留小数点后两位 - CSDN博客
查看>>
js 不固定传参
查看>>
远程调试UWP遇到新错误Could not generate the root folder for app package ......
查看>>
[倍增][最短路-Floyd][dp]
查看>>
SpringAOP用到了什么代理,以及动态代理与静态代理的区别
查看>>
利用STM32CubeMX来生成USB_HID_Mouse工程【添加ADC】(1)
查看>>
【leetcode】Populating Next Right Pointers in Each Node
查看>>
获取请求参数乱码的问题
查看>>
代码实现:判断E盘目录下是否有后缀名为.jpg的文件,如果有,就输出该文件名称...
查看>>
Android客户端测试点
查看>>
Jquery:怎样让子窗体的div显示在父窗体之上
查看>>
01概率
查看>>
Shell脚本
查看>>
MatLab Load cv::Mat 导入数据
查看>>
html+css相关笔记(一)
查看>>
基于块流协议保证音频优先发送
查看>>
关于互联网的一些数据
查看>>
数据预处理:独热编码(One-Hot Encoding)
查看>>
python将对象名的字符串类型,转化为相应对象的操作方法
查看>>