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 the Sum of three numbers by LeetCode

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly introduces LeetCode how to solve the problem of the sum of three numbers, the article introduces in great detail, has a certain reference value, interested friends must read it!

one

Topic description

Given an integer array nums, it is judged whether there are three elements in nums, such that a + b + c = 0. If there is no return [], if there is, return all the answers that meet the criteria and do not repeat. For example, input [- 1mem0pence2jormae1mae4] returns [[- 1jie0recovery1], [- 1maimel 1mem2]], and returns [] if you enter [- 3jue 3].

two

Solve a problem

This question needs two predictions: 1, when the length of the array is less than 3, the direct output []; 2, the array is sorted first, if the current number is the same as the previous one, the results will be the same, just skip it.

Idea 1: hash table

This problem is to find the three elements that meet the conditions. When the first element an is fixed, the problem is transformed into the problem of finding b and c to make the sum of-a, which is consistent with the problem in LeetCode exercise DAY 8: the sum of two numbers, so it can also be solved by hash table.

Class Solution: def threeSum (self, nums: List [int])-> list [int]: if len (nums) 0 and nums [I] = = nums [I-1]: continue h_map = {} target =-nums [I] for j in range (iTun1) Len (nums): if target-nums [j] in h_map: a.append (sorted ([nums [I], nums [j], target- nums [j])) h _ map [nums [j]] = j return list (set ([tuple (t) for t in a]))

Idea 2: double pointers

When the array is sorted and the first element an is fixed, the problem is the same as the problem in LeetCode exercise DAY 9: the sum of two numbers II, and can be solved by double pointer method.

Class Solution: def threeSum (self, nums: List [int])-> list [int]: if len (nums) 0 and nums [I] = nums [I-1]: continue x = len (nums)-1 target =-nums [I] while x

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