๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/Leetcode

[Leetcode,c++] Find First and Last Position of Element in Sorted Array

by dkswnkk 2021. 11. 14.

๋ฌธ์ œ

 

Find First and Last Position of Element in Sorted Array - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

์ฝ”๋“œ

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

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

        int first_index = -1,last_index = -1;
        vector<int>ans;

        while(start<=end){
            int mid = (start+end)/2;
            if(nums[mid]>target) end=mid-1;
            else if(nums[mid]<target) start=mid+1;
            else{
                first_index = last_index = mid;
                break;
            }
        }

        int index = first_index;

        while(--index>=0&&nums[index]==target) first_index--;

        index = last_index;

        while(++index<nums.size()&&nums[index]==target) last_index++;

        ans.emplace_back(first_index);
        ans.emplace_back(last_index);

        if(ans.size()==0||index == -1) return {-1,-1};
        return ans;
    }
};

 

ํ’€์ด

๊ธฐ๋ณธ์ ์ธ ์ด๋ถ„ ํƒ์ƒ‰์„ ํ†ตํ•ด์„œ target์˜ index๋ฒˆํ˜ธ๋ฅผ ์ผ๋‹จ ๋จผ์ € ์ฐพ์Šต๋‹ˆ๋‹ค. ๊ทธ ํ›„ ๊ทธ ์ธ๋ฑ์Šค ๋ฒˆํ˜ธ๋ฅผ ๊ธฐ์ ์œผ๋กœ ์ขŒ ์šฐ๋กœ ํผ์ ธ ๋‚˜๊ฐ€๋ฉด์„œ ๋‹ค๋ฅธ ๊ฐ’์ด ๋‚˜์˜ฌ ๋•Œ๊นŒ์ง€ ์ฐพ์œผ๋ฉด target์˜ ์‹œ์ž‘ index์™€  ๋ index๋ฅผ ์ฐพ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

'Algorithm ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป > Leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Leetcode,c++] Rotate Image  (0) 2021.11.15
[Leetcode,c++] Permutations II  (0) 2021.11.15
[Leetcode,c++] Roman to Integer  (0) 2021.11.15
[Leetcode,c++] Group Anagrams  (0) 2021.11.14
[Leetcode,c++] Next Permutation  (0) 2021.11.14
[Leetcode,c++] Length of Last Word  (0) 2021.11.14

๋Œ“๊ธ€