【问题标题】:What's wrong with my solution of SearchInsert?我的 SearchInsert 解决方案有什么问题?
【发布时间】: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 &lt;= end) { return target &lt;= nums[start] ? start : (start+1); }你可以进一步调试。
  • 如果您提供所有代码会有所帮助
  • 请阅读minimal reproducible example,并注意阅读页面底部链接的有关调试的文章。
  • 有一个主要的方法使它成为一个 MCVE。嗬嗬嗬。

标签: java algorithm search


【解决方案1】:

条件:

start <= end

不正确。对于非零长度数组,条件立即为真,因为start == 0end == &lt;something which is at least 0&gt;,所以它会立即返回startstart+1 - 在你的情况下,start+1

【讨论】:

  • 好吧,我在这里犯了一个愚蠢的错误,浪费了这么多时间来找出为什么这段代码不起作用。应该是start &gt;= end:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多