Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to solve the problem of the Sum of three numbers by LeetCode

Shulou Source: shulou.com Published: 2022-06-01 13:20:47 11月14日 Update

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

Tags: Question sum element array consistency topic three content idea pointer method topic condition article hash sort input same value interest Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL OPPO Reno Docker Xiaomi Redmi