Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Case Analysis of python search insertion location

Shulou Source: shulou.com Published: 2022-05-31 14:07:57 10月05日 Update

This article mainly introduces "python search insertion location instance analysis". In daily operation, I believe many people have doubts about python search insertion location instance analysis. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "python search insertion location instance analysis". Next, please follow the editor to study!

[title]

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, 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

[ideas]

1. Brute force solution: traversing the array to find elements.

2. Binary search: the question type is to find the first element greater than or equal to target and return its location.

Binary search generally uses common code:

I, j = 0, len (nums)-1

While i target:

J = mid-1

Else:

I = mid + 1

Return i

At the end of the # loop, the result is the operator in the formula nums [j] target, and the returned subscript, which are also parts of the general code that must be modified according to the title.

# when nums [mid] > target, the final result nums [j] = target, the final result nums [j]

< target int: l, r = 0, len(nums) - 1 # 第一个 >

Elements of = target

# nums [r] < target

Tags: Location array result instance instance analysis analysis search element example topic learning input output code goal target value more help loop practical Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi macOS Huawei vpn Microsoft