Rylah's Study & Daily Life

01. LeetCode 704 - Binary Search 본문

LeetCode

01. LeetCode 704 - Binary Search

Rylah 2022. 1. 11. 16:27

LeetCode 704. Binary Search

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

#include <iostream>
#include <vector>

int binary_search(std::vector<int>& nums, int target)
{
	int left = 0;
	int right = (int)nums.size() - 1;

	while (left <= right)
	{
		int pivot = (left + right) / 2;
		if (nums[pivot] == target)
			return pivot;
		else if (nums[pivot] < target)
			left = pivot + 1;
		else // nums[pivot] > target
			right = pivot - 1;
	}
	return -1;
}
int main(void)
{
	std::vector<int> v{ -1, 0, 3, 5, 9, 12 };
	int target = 9;
	std::cout << binary_search(v, target) << '\n';
	return 0;
}

Binary Search를 하기 위해서는 자료가 정렬되어 있어야 되는 것을 잊지말자.

 

기본적인 Binary Search를 묻는 문제이다.

'LeetCode' 카테고리의 다른 글

03. LeetCode 724. Find Pivot Index  (0) 2022.01.11
02. LeetCode 283. Move Zeroes  (0) 2022.01.11