我的SearchInsert解决方案有什么问题?

时间:2015-12-23 12:49:43

标签: java algorithm search

之谜:

  

给定排序数组和目标值,如果找到目标,则返回索引。如果没有,请返回索引按顺序插入的索引。

     

您可以假设数组中没有重复项。

我的代码在这里:

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

请提前帮助我。

1 个答案:

答案 0 :(得分:1)

条件:

start <= end

不正确。对于非零长度数组,条件立即成立,因为start == 0end == <something which is at least 0>,因此它会立即返回startstart+1 - 在您的情况下,{ {1}}。

相关问题