首页 > 其他分享 >LeetCode 34. Find First and Last Position of Element in Sorted Array

LeetCode 34. Find First and Last Position of Element in Sorted Array

时间:2022-10-18 14:03:54浏览次数:79  
标签:back Last nums mid Element start ans end LeetCode

​题目​

二分练习

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {

vector<int> ans;
if(nums.size()==0)
{
ans.push_back(-1);
ans.push_back(-1);

return ans;
}

int start = 0;
int end = nums.size()-1;


while(start<=end)
{
int mid = (start+end)/2;

if(nums[mid]>=target)
{
end = mid-1;
}
else if(nums[mid]<target)
{
start = mid+1;
}
}

if(start==nums.size()||nums[start]!=target){
ans.push_back(-1);
ans.push_back(-1);

return ans;
}
ans.push_back(start);
start=0;
end=nums.size()-1;

while(start<=end)
{
int mid = (start+end)/2;

if(nums[mid]>target)
{
end = mid-1;
}
else if(nums[mid]<=target)
{
start = mid+1;
}
}

ans.push_back(end);

return ans;


}
};



标签:back,Last,nums,mid,Element,start,ans,end,LeetCode
From: https://blog.51cto.com/u_15834522/5766284

相关文章

  • LeetCode 76. Minimum Window Substring
    ​​题目​​从第一个字符串中找到最小的子串,让子串中包含第二个字符串中的每一个字符。我的思路来自滑动窗口思想,之前用来做自动摘要的。把第一个字符串中的在第二个字符串......
  • LeetCode 36. Valid Sudoku
    ​​题目​​classSolution{public:inttag[10];boolisValidSudoku(vector<vector<char>>&board){for(inti=0;i<9;i++){......
  • LeetCode 54. Spiral Matrix
    ​​题目​​水题classSolution{public:vector<int>spiralOrder(vector<vector<int>>&matrix){inti=0,j=0;vector<int>ans;int......
  • LeetCode 33 Search in Rotated Sorted Array
    ​​题目​​c++二分classSolution{public:intsearch(vector<int>&nums,inttarget){if(nums.size()==0)return-1;intsta......
  • LeetCode 70. Climbing Stairs
    ​​题目​​classSolution{public:intdp[10005];intclimbStairs(intn){dp[1]=1;dp[2]=2;for(inti=3;i<=n;i++)......
  • LeetCode 53. Maximum Subarray
    ​​题目​​简单DPclassSolution{public:intdp[100005];intmaxSubArray(vector<int>&nums){if(nums.size()==0)return0;......
  • LeetCode 69. Sqrt(x)
    ​​题目​​classSolution{public:intmySqrt(intx){longlonginty=x;intl=0;intr=(x==1?1:x/2);while(l<=r){......
  • Elasticsearch 6.8.6
     mac;centos;unix; 下载wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.8.6.tar.gz windows下载(迅雷)​​https://artifacts.elastic.c......
  • [答疑]Clone Elements为什么是灰的
    问题:这一项为啥是灰的以下为单宝华贡献的回答2020-5-2421:29参考⽂档https://sparxsystems.com/enterprise_architect_user_guide/14.0/model_domains/clone_element_as_n......
  • elementui表格实现单选功能(带多选框)
    1. 2.  3.样式  4.实现效果   ......