微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

LeetCode开心刷题十八天——34. Find First and Last Position of Element in Sorted ArrayEasy

ATTENTION:only thing need to pay attention is the loop condition is left<=right,don;t forget =
PROBLEM:my code is long,there must some easier way to design it
34. Find First and Last Position of Element in Sorted Array
Medium

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 = [,target = 8
Output: [3,4]5,7,8,10]

Example 2:

Input: nums = [,target = 6
Output: [-1,-1]

Answer Code:5,10]
#include<stdio.h>
#include<iostream>
#include<vector>
#include<algorithm>
#include<stack>
#include<string>

using namespace std;
class Solution {
public:
    vector<int> searchRange(vector<int>& nums,int target) {
        int n=nums.size();
        cout<<"n:"<<n<<endl;
        vector<int> res;
        if(n==1)
        {
            if(target==nums[0])
            {
                res.push_back(0);
                res.push_back(0);
                return res;
            }
            else
            {
                res.push_back(-1);
                res.push_back(-1);
                return res;
            }
        }
        int left=0,right=n-1;
        int flag=0,mid=0;
        while(left<=right)
        {
            mid=(left+right)/2;
            cout<<"mid:"<<mid<<endl;
            if(nums[mid]==target)
            {
                flag=1;
                break;
            }
            if(nums[mid]>target)
            {
                right=mid-1;
            }
            else if(nums[mid]<target)
            {
                left=mid+1;
                //cout<<"left:"<<left<<endl;
            }
        }
        if(flag==0)
        {
            res.push_back(-1);
            res.push_back(-1);
            return res;
        }
        else if(flag==1)
        {
            int temp=mid,temp1=mid;
            //cout<<"mid:"<<mid<<endl;
            cout<<"n:"<<n<<endl;
            while(temp>0&&nums[temp]==nums[temp-1])
            {
                temp--;
            }
            while(temp1<n-1&&nums[temp1]==nums[temp1+1])
            {
                temp1++;
            }
            res.push_back(temp);
            res.push_back(temp1);
        }
        return res;
    }
};
int main()
{
    int target=4;
    vector<int> a,res;
    a.push_back(1);
    a.push_back(4);
 //   a.push_back(2);
//    a.push_back(8);
//    a.push_back(8);
//    a.push_back(10);
    Solution s;
    res=s.searchRange(a,target);
    for(auto t:res)
    {
        cout<<t<<endl;
    }
    return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。