문제
public class Solution {
public static void main(String[] args) {
System.out.println(search(new int[]{-1,0,3,5,9,12}, 9));
System.out.println(search(new int[]{-1,0,3,5,9,12}, 2));
System.out.println(search(new int[]{2,5}, 2));
System.out.println(search(new int[]{5}, 5));
}
public static int search(int[] nums, int target) {
}
}
결과 및 풀이
public static int search(int[] nums, int target) {
int endIndex = nums.length - 1;
int startIndex = 0;
int mid;
while (startIndex <= endIndex) {
mid = (endIndex + startIndex) / 2;
if(target == nums[mid]) {
return mid;
} else if (target > nums[mid]) {
startIndex = mid + 1;
} else {
endIndex = mid - 1;
}
}
return -1;
}
배웠다
- 중간값을 구하는 식은 (startIndex+endIndex)/2
- 이건 좀 외우자.. 잘 못풀어서 충격이다…