谜题:
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.
还有我的代码:
public class Solution {
public static int searchInsert(int[] nums, int target) {
return searchInsert(nums, target, 0, nums.length-1);
}
private static int searchInsert(int[] nums, int target, int start, int end) {
if(start <= end) {
return target <= nums[start] ? start : (start+1);
}
int m = (start + end) / 2;
if(nums[m] == target) {
return m;
} else if(nums[m] < target) {
return searchInsert(nums, target, m+1, end);
} else {
return searchInsert(nums, target, start, m-1);
}
}
public static void main(String[] args) {
int[] nums = {1, 3};
System.out.print(searchInsert(nums, 4);
}
}
结果是这样的:
Input:
[1,3]
4
Output:
1
Expected:
2
我在纸上一遍又一遍地模拟了这个输入的过程,就是想不通我的代码怎么能输出2
。
请提前帮我解决这个问题。
最佳答案
条件:
start <= end
不正确。对于非零长度数组,条件立即为真,因为 start == 0
和 end == <something which is at least 0>
, 所以它会返回 start
或 start+1
马上 - 在你的情况下,start+1
.
关于java - 我的 SearchInsert 解决方案有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34436108/