In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
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)
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.