Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Case Analysis of python search insertion location

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report