题目:搜索插入位置

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

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

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

我发现网上大多都是用二分查找来解决的,其实并不需要。

条件:

有序数组,无重复元素

解题思路:

(1) nums数组中存在target值,遍历数组target==nums[i],返回i;

(2) nums数组中不存在target值,遍历数组找到target<nums[i],返回i;//有序数组

注意:当target大于nums数组的最大值,target==nums.length,所以我们只需要把变量 i 的定义放在循环外,就可以了。

综上所述,target要插入的位置只需满足target<=nums[i],返回 i。

leetcode-35 搜索插入位置(SearchInsertPosition)-java

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-08-26
  • 2021-06-22
  • 2021-07-08
猜你喜欢
  • 2021-12-27
  • 2022-01-20
  • 2021-08-27
  • 2021-12-10
  • 2022-12-23
  • 2021-10-29
  • 2021-07-10
相关资源
相似解决方案