짱아의 개발 기록장

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

Algorithm/LeetCode

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

jungahshin 2021. 1. 13. 13:10
반응형

이분탐색 문제이다.

 

[메인 로직]

low, high값을 잡고 mid가 target과 같을 때, 작을 때, 클 때를 나누어서 구현하면 된다.

같을 때 -> 위, 아래로 같은 값이 나오면 탐색한다.

작을 때 -> 정렬된 상태이기 때문에 low = mid+1;

클 때 - > high = mid-1;

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int low = 0;
        int high = nums.size()-1;
        int Start = 0, End = 0;
        vector<int> ans;
        bool check = false;
        
        if(nums.size()==1){
            if(nums[0]==target){
                check = true;
            }
        }
        
        while(low<=high){
            int mid = (low+high)/2;
            if(nums[mid]==target){
                check = true;
                Start = mid, End = mid;
                while(End<nums.size()-1 && nums[End]==nums[End+1]){
                    End++;
                }
                while(Start>0 && nums[Start]==nums[Start-1]){
                    Start--;
                }
                break;
            }else if(nums[mid]>target){
                high = mid-1;
            }else{
                low = mid+1;
            }
        }
        
        if(check==true){
            ans.push_back(Start);
            ans.push_back(End);            
        }else{
            ans.push_back(-1);
            ans.push_back(-1);
        }
 
        return ans;
    }
};
cs
반응형

'Algorithm > LeetCode' 카테고리의 다른 글

LeetCode : 122. Best Time to Buy and Sell Stock II  (0) 2021.01.14
LeetCode : 55. Jump Game  (0) 2021.01.14
LeetCode : 4. Median of Two Sorted Arrays  (0) 2021.01.13
LeetCode : 16. 3Sum Closest  (0) 2021.01.12
LeetCode : 15. 3Sum  (0) 2021.01.11
Comments