문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
오름차순으로 정렬된 정수 배열 nums와 정수 target이 주어졌을 때, nums에서 target을 찾는 함수를 작성해라. trget이 존재하면 해당 인덱스를 반환하고, 그렇지 않으면 -1을 반환해라.
#1
Input: nums = [-1, 0, 3, 5, 9, 12], target = 9
Output: 4
Explanation: 9는 nums에 존재하고, 해당 인덱스는 4이다.
#2
Input: nums = [-1, 0, 3, 5, 9, 12], target = 2
Output: -1
Explanation: 2는 nums에 존재하지 않아서 -1을 반환한다.
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while(left <= right){
int mid = left + (right - left) / 2;
if(nums[mid] == target) return mid;
else if(nums[mid] < target) left = mid + 1;
else if(nums[mid] > target) right = mid - 1;
}
return -1;
}
}