思路: binary search。代码:
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while(right >= left){
int pivot = left + (right - left) / 2; //prevent overflow
if(target == nums[pivot]){return pivot;}
else if(target < nums[pivot]){right = pivot - 1;}
else{left = pivot + 1;}
}
return left;
}
}
总结:
- binary search是重要算法!
- Arrays.asList常见错误: