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

标签 java algorithm search

谜题:

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 == 0end == <something which is at least 0> , 所以它会返回 startstart+1马上 - 在你的情况下,start+1 .

关于java - 我的 SearchInsert 解决方案有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34436108/

相关文章:

java - 如何将扩展类从 DailyRollingFileAppender 转换为 Log4j 2

c++ - 整数阈值

jquery - 使用 jQuery 过滤带有 on data 属性的表

algorithm - 爬山搜索算法应用于旅行商

java - 使用Java反射加载接口(interface)

java - 如何在由azure应用程序服务门户UI部署的azure java应用程序中配置Web.config文件

java - 无法在 if 语句中向变量添加数字

algorithm - 有序集和自然双射(组合物种)

c++ - 查找输入数字以了解它在数组中的位置

sql-server - OData 适用于 Multi-Tenancy LOB 应用吗?