LeetCode 35. 搜索插入位置
/** * 二分查找思想 */ class Solution { public int searchInsert(int[] nums, int target) { int len = nums.length; //判空 if(len == 0) { return 0; } //如果最后一个元素都没target大,将它插到最后 if(nums[len - 1] < target){ return len; } int low = 0; int high = len - 1; while(low < high){ int mid = low + (high - low) / 2; if(nums[mid] < target){ //下一轮搜索区间是 [mid + 1, right] low = mid + 1; } else { high = mid; // 下一轮搜索区间是 [left, mid] } } return low; } }