您好,欢迎来到爱站旅游。
搜索
您的当前位置:首页【LeetCode】Search Insert Position(搜索插入位置)

【LeetCode】Search Insert Position(搜索插入位置)

来源:爱站旅游

这道题是LeetCode里的第35道题。

题目描述:

二分查找,简单快捷。每一次将被查找区间分为两块,然后再与该区间的中间值比较,根据比较的结果判断是左边还是右边。

解题代码:

class Solution {
    public static int find(int[] nums, int start, int end, int target) {
        if (start >= end) {
            if (target <= nums[start])
                return start;
            else
                return start + 1;
        }
        int half = (start + end) / 2;
        if (target == nums[half])
            return half;
        else if (target > nums[half])
            return find(nums, half + 1, end, target);
        else
            return find(nums, start, half - 1, target);
    }

    public static int searchInsert(int[] nums, int target) {
        if (nums.length == 0)
            return 0;
        // if(nums.length == 1)return find(nums, 0 ,0, target);

        int half = (nums.length) / 2;
        if (target == nums[half])
            return half;
        else if (target > nums[half])
            return find(nums, half, nums.length - 1, target);
        else
            return find(nums, 0, half - 1, target);
    }
}

提交结果:

个人总结:

这道题算是二分查找的入门题。

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- azee.cn 版权所有 赣ICP备2024042794号-5

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务