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
반응형
'Problem Solving' 카테고리의 다른 글
[C++] [LeetCode 206] Reverse Linked List (0) | 2021.08.09 |
---|---|
[C++] [LeetCode 26] Remove Duplicates from Sorted Array (0) | 2021.08.09 |
[C++] [LeetCode 35] Search Insert Position (0) | 2021.08.09 |
[C++] [백준 11650] 좌표 정렬하기 (0) | 2021.07.27 |
[C++] [백준 1427] 소트인사이드 (0) | 2021.07.27 |
댓글