본문 바로가기
Algorithm

[Algorithm][Recursion] 문제 풀이 #21 - Binary Search

by Lee David 2022. 8. 6.
반응형
문제 링크

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

풀이
public int search(int[] nums, int target) {
    int start = 0;
    int end = nums.length - 1;

    while(start <= end) {
        int mid = (end - start) / 2 + start;

        if(target < nums[mid]) end = mid - 1;
        else if (target > nums[mid]) start = mid + 1;
        else return mid;
    }

    return -1;
}
결과

이진 검색을 사용해서 쉽게 풀수 있었다.

역시 easy는 easy

 

 

 

 

 

 

 

반응형