반응형
https://leetcode.com/problems/binary-search/description/
Binary Search - LeetCode
Can you solve this real interview question? Binary Search - Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
leetcode.com
이진 탐색 문제였습니다.
class Solution {
public:
int search(vector<int>& nums, int target) {
int l = 0, r = nums.size() - 1;
while(l <= r) {
int m = (l + r) / 2;
if(nums[m] == target) return m;
else if(nums[m] > target) r = m - 1;
else l = m + 1;
}
return -1;
}
};
반응형
'Algorithm' 카테고리의 다른 글
LeetCode 881. Boats to Save People (0) | 2023.04.03 |
---|---|
LeetCode 2300. Successful Pairs of Spells and Potions (0) | 2023.04.02 |
LeetCode 87. Scramble String (0) | 2023.03.30 |
LeetCode 1402. Reducing Dishes (0) | 2023.03.29 |
LeetCode 983. Minimum Cost For Tickets (0) | 2023.03.29 |