본문 바로가기
Problem Solving/LeetCode

[LeetCode] 704. Binary Search - Java

by graycode 2026. 9. 29.

• 문제 링크

 

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

 

• 풀이 코드

public class Solution {

    public int search(int[] nums, int target) {
        int l = 0, r = nums.length - 1, i = -1;
        while (l <= r) {
            int m = l + (r - l) / 2;
            if (nums[m] >= target) {
                r = m - 1;
                i = m;
            } else l = m + 1;
        }

        return i != -1 && nums[i] == target ? i : -1;
    }

}

댓글