티스토리 뷰
알고리즘 문제 풀이
[알고리즘문제] 릿코드 Find First and Last Position of Element in Sorted Array
kmj24 2021. 10. 11. 22:22https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
정렬된 number타입 배열과 number타입 value가 들어온다.
배열에서 value가 존재하는 start index와 end index를 return 한다.
조건은 Time complexity는 O(logn)이 되어야 한다.
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
if (nums.size() == 0) return { -1, -1 };
vector<int> answer = { -1, -1 };
int start = 0;
int end = nums.size() - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (nums[mid] == target) {
while (nums[start] != target) {
start++;
}
while (nums[end] != target) {
end--;
}
answer[0] = start;
answer[1] = end;
return answer;
}
else if(nums[mid] < target){
// 하위 idx 탐색
start = mid + 1;
}
else {
// 상위 idx 탐색
end = mid - 1;
}
}
return answer;
}
};
'알고리즘 문제 풀이' 카테고리의 다른 글
[알고리즘문제] 릿코드 Find Kth Bit in Nth Binary String (0) | 2021.09.25 |
---|---|
[알고리즘문제] 백준 부분수열의 합 (0) | 2021.08.25 |
[알고리즘문제] 백준 단어나누기 (0) | 2021.08.24 |
[알고리즘문제] 백준 9012 괄호 (0) | 2021.08.15 |
[알고리즘문제] 릿코드 Pascal's Triangle (0) | 2021.07.10 |