๋ฌธ์
์ฝ๋
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 |
๋๊ธ