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

How to solve the problem of binary search in leetcode

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

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail how to solve the problem of binary search in leetcode. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

Topic link

Https://leetcode-cn.com/problems/binary-search/

Topic description

Given an ordered (ascending) integer array of n elements nums and a target value target, write a function to search for target in nums, and return subscript if the target value exists, otherwise return-1.

Example 1:

Input: nums = [- 1 nums 0 ~ 3 ~ 5 ~ 9 ~ 12], target = 9 output: 4 explain: 9 appears in nums and the subscript is 4.

Example 2:

Input: nums = [- 1 nums 0 ~ 3 ~ 5 ~ 9 ~ 12], target = 2 output:-1 explain: 2 does not exist in nums and therefore returns-1

Tip:

You can assume that all elements in nums are not duplicated.

N will be between [1, 10000].

Each element of nums will be between [- 9999, 9999].

The idea of solving the problem

Tags: binary search

Process:

Set the left and right pointer

Find out the middle position and determine whether the position value is equal to target

Nums [mid] = = target returns the location subscript

Nums [mid] > target moves the right pointer to the middle

Nums [mid]

< target 则左侧指针移到中间 时间复杂度:O(logN) 画解

Code class Solution {public int search (int [] nums, int target) {int left = 0, right = nums.length-1; while (left target) {right = mid-1;} else {left = mid + 1;}} return-1 }} this is the end of the article on "how to solve the binary search problem in leetcode". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

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