public class Solution { public int searchInsert(int[] nums, int target) { if(nums == null || nums.length == 0) { return 0; } int res = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] == target) { return i; } if (nums[i] < target) { continue; } if (nums[i] > target) { res = i; return res; } } res = nums.length; return res; } }
以上是自己写的
参考九章答案:用二分
find the first position >= target
public class Solution { public int searchInsert(int[] nums, int target) { int start = 0; int end = nums.length -1; while (start + 1 < end) { int mid = start + (end - start)/2; if (nums[mid] == target) { return mid; } else if (nums[mid] < target) { start = mid; } else { end = mid; } } if (nums[start] >= target) { return start; } else if (nums[end] >= target) { return end; } else { return end+1; } } }
find the last position <= target
public class Solution { public int searchInsert(int[] A, int target) { int start = 0; int end = A.length - 1; int mid; if (target < A[0]) { return 0; } // find the last number less than target while (start + 1 < end) { mid = start + (end - start) / 2; if (A[mid] == target) { return mid; } else if (A[mid] < target) { start = mid; } else { end = mid; } } if (A[end] == target) { return end; } if (A[end] < target) { return end + 1; } if (A[start] == target) { return start; } return start + 1; } }
时间: 2024-10-26 14:54:50