Leetcode 35——Search Insert Position

时间:2023-03-08 21:33:02

  Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

  You may assume no duplicates in the array.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 1:

Input: [1,3,5,6], 0
Output: 0 很简单的一个题目,找有序数列里的目标数的下标,找不到就返回可以插入的下标。既然已经排好序,直接用二分法查找即可,一次提交就A掉。上代码。
public static int searchInsert(int[] nums, int target) {
if (nums.length == 0||target<nums[0])
return 0;
if(target>nums[nums.length-1])return nums.length; int low, high;
low = 0;
high = nums.length - 1;
while (nums[(low + high) / 2] != target) {
if (low<high) {
if (nums[(low + high) / 2] > target) { high = (low + high) / 2;
} else if (nums[(low + high) / 2] < target) {
if(low==(low + high) / 2)return (low + high) / 2+1;
low = (low + high) / 2;
} else {
return (low + high) / 2;
}
}
} return (low + high) / 2;
}