본문 바로가기
Problem Solving

[C++] [LeetCode 704] Binary Search

by tls1107 2021. 8. 9.
728x90
반응형


문제 풀기 전 생각 : 

/*
find 함수를 사용한다.
만약 존재하지 않는다면 -1을 리턴하고
존재한다면 find 함수에서 얻은 값에서 begin iterator를 뺸 값을 리턴한다.
*/

class Solution {
public:
    int search(vector<int>& nums, int target) {
        auto it = find(nums.begin(), nums.end(), target);
        if(it == nums.end()) return -1;
        return it-nums.begin();
    }
};

https://leetcode.com/problems/binary-search/

 

Binary Search - 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:
    int search(vector<int>& nums, int target) {
        int start = 0;
        int end = nums.size() - 1;
        while(start<=end){
            int mid = (start + end)/2;
            if(nums[mid] == target){
                return mid;
            }
            else if(nums[mid]<target){
                start = mid + 1;
            }
            else{
                end = mid - 1;
            }
            
        }
        
        return -1;
    }
};

직접 구현하면 이렇게 구현하면 되는듯 하다

 

728x90
반응형

댓글