【LeetCode】 35. Search Insert Position 搜索插入位置(Easy)(JAVA)

【LeetCode】 35. Search Insert Position 搜索插入位置(Easy)(JAVA)

题目地址: https://leetcode.com/problems/search-insert-position/

题目描述:

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

题目大意

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

你可以假设数组中无重复元素。

解题方法

对有序数列查找指定元素,用二分查找即可

class Solution {
    public int searchInsert(int[] nums, int target) {
        int start = 0;
        int end = nums.length - 1;
        while (start <= end) {
            int mid = start + (end - start) / 2;
            if (nums[mid] == target) return mid;
            if (nums[mid] > target) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return start;
    }
}

执行用时 : 0 ms, 在所有 Java 提交中击败了 100.00% 的用户
内存消耗 : 39 MB, 在所有 Java 提交中击败了 30.33% 的用户

发布了81 篇原创文章 · 获赞 6 · 访问量 2307

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/104650726