LeetCode刷题系列—35. Search Insert Position

1.题目描述

英文版:

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.

Example 1:

Input: [1,3,5,6], 5

Output: 2

Example 2:

Input: [1,3,5,6], 2

Output: 1

Example 3:

Input: [1,3,5,6], 7

Output: 4

Example 4:

Input: [1,3,5,6], 0

Output: 0

中文版:

给一个有序数组和目标值,如果存在则返回它的角标,

如果不存在,则返回它在数组中应该插入的位置。

假设数组中不存重复的元素。

例 1:

输入: [1,3,5,6], 5

输出: 2

例 2:

输入: [1,3,5,6], 2

输出: 1

例 3:

输入: [1,3,5,6], 7

输出: 4

Example 4:

输入: [1,3,5,6], 0

输出: 0

2.解法

2.1 解法1

思路:

    public static int searchInsert1(int[] nums, int target) {
        for(int i = 0;i < nums.length;i++){
            if (nums[i] >= target){
                return i;
            }
        }
        return nums.length;
    }

在LeetCode上运行的结果:

2.2 解法2

思路:

    public static int searchInsert(int[] nums, int target) {
        if(target > nums[nums.length - 1]){
            return nums.length;
        }
        int left = 0;
        int right = nums.length - 1;
        while (left < right){
            int middle = left + (right - left) / 2;
            if (target < nums[middle]){
                right = middle;
            }else if(target > nums[middle]){
                left = middle + 1;
            }else {
                return middle;
            }
        }
        return right;
    }

在LeetCode上运行的结果:

3.测试

在本地,我只是简单写了一个main函数来对它进行测试。但是这些代码都是在LeetCode上运行通过了的。

    public static void main(String[] args) {
        int[] nums = {1,3,5,6};
        int target = 2;
        int result = searchInsert(nums,target);
        System.out.println(result);
    }
欢迎关注个人公众号,可直接扫描以下二维码或微信搜索“阿毛聊技术”。

猜你喜欢

转载自www.cnblogs.com/limaodeng/p/12358989.html