Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use java to search for insertion location

Shulou Source: shulou.com Published: 2022-06-01 01:11:53 09月10日 Update

This article mainly introduces how to use java to achieve search insertion location, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.

Topic description

Given a sorted array and a target value, find the target value in the array and return its index. If the target value does not exist in the array, returns the position where it will be inserted sequentially.

You can assume that there are no repeating elements in the array.

Example 1:

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

Example 2:

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

Example 3:

Input: [1, 3, 5, 6], 7, output: 4.

Example 4:

Input: [1Jing 3jue 5jue 6], 0 output: 0 problem solving ideas

Tags: binary search

The time complexity of O (n) is needed if the problem is solved violently, but it can be reduced to O (logn) if it is divided into two parts.

The overall idea is almost no different from the ordinary binary search, first set the left subscript left and the right subscript right, and then calculate the intermediate subscript mid

Each time the judgment is made according to the size of nums [mid] and target, if the same is equal, the subscript is returned directly, and the nums [mid] target is moved to the left of right.

At the end of the search, if there is no equivalent, left is returned, which is the insertion position.

Time complexity: O (logn)

The idea of binary search is not difficult to understand, but the boundary conditions are prone to errors, such as the relationship between left and right in the loop end condition, and whether to add 1 minus 1 when updating left and right positions.

Here are two templates that can be applied directly. Just remember to avoid boundary condition errors.

Class Solution {public int searchInsert (int [] nums, int target) {int left = 0, right = nums.length-1; / / Note while (left)

Tags: Location subscript array example article input output complexity complexity idea time condition goal target value search boundary logic topic general two Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft MariaDB Xiaomi NVidia MySQL