• 문제 링크
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;
}
}'Problem Solving > LeetCode' 카테고리의 다른 글
| [LeetCode] 706. Design HashMap - Java (0) | 2026.10.01 |
|---|---|
| [LeetCode] 705. Design HashSet - Java (0) | 2026.09.30 |
| [LeetCode] 703. Kth Largest Element in a Stream - Java (0) | 2026.09.28 |
| [LeetCode] 700. Search in a Binary Search Tree - Java (0) | 2026.09.27 |
| [LeetCode] 697. Degree of an Array - Java (0) | 2026.09.26 |
댓글