Leetcode 35) Search Insert Position
in Algorithms
My Answer
class Solution {
public int searchInsert(int[] nums, int target) {
int left=0;
int right = nums.length-1;
while(left < right){
//till when the left and right pointer is overlapped
int mid= (left+right)/2;
if(nums[mid]<target){
//이 경우에는, mid 가 left bias한 점이 걸리기 때문에, 이렇게 해줘야한다.
//mid == left 인 경우, 영원히 안 끝남.
left=mid+1;
}else{
right=mid;
}
}
if(right==nums.length-1){
if(nums[right]<target){
right++;
}
}
return right;
}
}
Other Answer
class Solution {
public int searchInsert(int[] nums, int target) {
int low = 0;
int high = nums.length-1;
while(low<=high){
int mid = (low + high)/2;
if(target==nums[mid]){
return mid;
}
if(nums[mid]<target){
low=mid+1;
}
else{
high = mid-1;
}
}
return low;
}
}
arraylist 다루는 법, 더 잘 알면 좋다.