【发布时间】:2015-12-23 12:49:42
【问题描述】:
谜题:
给定一个排序数组和一个目标值,如果找到目标则返回索引。如果不是,则返回按顺序插入的索引。
您可以假设数组中没有重复项。
我的代码在这里:
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);
}
}
结果是这样的:
输入:
[1,3]
4
输出:
1
预期:
2
我在纸上一遍又一遍地模拟了这个输入的过程,但就是不知道我的代码如何输出2。
请帮助我,谢谢。
【问题讨论】:
-
问题在这里结束了。
if(start <= end) { return target <= nums[start] ? start : (start+1); }你可以进一步调试。 -
如果您提供所有代码会有所帮助
-
请阅读minimal reproducible example,并注意阅读页面底部链接的有关调试的文章。
-
有一个主要的方法使它成为一个 MCVE。嗬嗬嗬。