# The sum of N numbers in [array]

## Leetcode 1. Sum of two numbers

### Title Description

Given an integer array nums and a target value target, please find the two integers with and as the target value in the array and return their array subscripts.
You can assume that each input corresponds to only one answer. However, you cannot reuse the same elements in this array.

Example:
Given nums = [2, 7, 11, 15], target = 9

Because nums + nums = 2 + 7 = 9
So return [0, 1]

Source: LeetCode

### Solving problems

Using hash table, we judge whether target nums [i] exists in iteration, and then store tmp and its index into hash table

Hash table can be represented by dictionary in python

### code implementation

```class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
ans_map = dict()
for i in range(0, len(nums)):  # While adding the numbers in the list to the dictionary, judge whether the difference between the two numbers exists in the dictionary
temp = target - nums[i]
if temp in ans_map:  # Judgement step
return [ans_map[temp], i]
ans_map[nums[i]] = i  # Add steps (remember to judge before adding to avoid key conflict)
```

Note: this problem is not suitable for using double pointers, because you need to sort the array first. After sorting, the index of the array will be scrambled, and the result requires the index of the returned number

## Leetcode 15. Sum of three numbers

### Title Description

Given a n array of N integers nums, judge whether there are three elements a, b, c in nums, so that a + b + c = 0? Find all triples that meet the conditions and are not repeated.

Note: the answer cannot contain duplicate triples.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

The required set of triples is:
[
[-1, 0, 1],
[-1, -1, 2]
]

Source: LeetCode

### Solving problems

1. Sort array
2. Define pointer i,left,right. Traverse I, turn the problem into finding nums[i]+nums[left]+nums[right]=0 in the array after I (that is, the sum of three numbers can be solved by using double pointers)
3. Pruning, removing weight

### code implementation

```# Double pointer, so fix a number first, and use double pointer to find the other two numbers. Remember to prune
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
rnums=[]              # Create a new list to return
nums.sort()       #Sort
n = len(nums)
for i in range(n):
if i > 0 and nums[i] == nums[i-1]: # Avoid duplicates
continue
if nums[i] > 0:# Reduce irrelevant calculation. When the setting value is greater than 0, the later ones are greater than 0. There is no need for calculation
break
left = i + 1
right = n -1
while left < right:
cur_num = nums[i] + nums[left] + nums[right]
if cur_num == 0:
tmp = [nums[i], nums[left], nums[right]]
rnums.append(tmp)
while left < right and nums[left]==nums[left+1]: # Duplicate removal
left += 1
while left < right  and nums[right]==nums[right-1]: # Duplicate removal
right -= 1
left += 1
right -= 1
elif cur_num > 0:
right -= 1
else:
left += 1
return rnums
```

## Leetcode 16. The closest sum of three numbers

### Title Description

Given an array of n integers nums and a target value target. Find three integers in nums so that their sum is closest to target. Returns the sum of the three numbers. Assume that there is only one answer for each group of input.

For example, given the array nums = [-1, 2, 1, - 4], and target = 1

The sum of the three numbers closest to target is 2. (- 1 + 2 + 1 = 2)

Source: LeetCode

### Solving problems

1. If the array length is less than 3, return []
2. Sort array
3. Traversing array
1. Skip repeating elements
2. Set left pointer and right pointer, when left < right, cycle
1. get_nums = nums[i] + nums[left] + nums[right], if get_nums = target, return target
2. If ABS (get num s - target) < ABS (res - target) indicates get num s is closer to the target, update res
3. Prune
4. Return result

### code implementation

```class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums or len(nums) < 3:  # Exclusion of special circumstances
return None
nums.sort()
res = float("inf")  # py for positive infinity
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i - 1]:    # Remove weight and improve efficiency
continue
left = i + 1
right = len(nums) - 1
while left < right:
get_nums = nums[i] + nums[left] + nums[right]
if get_nums == target:
return target
if abs(get_nums - target) < abs(res - target):  # It indicates that get ﹣ nums is closer to the target
res = get_nums  # Update content
if get_nums - target < 0:
left += 1
else:
right -= 1
return res
```

## The sum of four numbers

### Title Description

Given a n array of N integers nums a n d a target value target, judge whether there are four elements a, b, c and D in nums, so that the value of a + b + c + d is equal to target? Find all quads that meet the conditions and are not repeated.

Be careful:

Example:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

The set of quads that meet the requirements is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]

Source: LeetCode

### Solving problems

1. sort
2. Use double loop to fix two numbers, use double pointer to find the other two numbers, and move the pointer by comparing the target size
3. Pruning, removing weight

### code implementation

```class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
nums.sort()
n = len(nums)
for a in range(n - 3):
# Prevent duplication
if a > 0 and nums[a] == nums[a - 1]:
continue
# When the sum of minimum values is greater than target, jump out
if nums[a] + nums[a + 1] + nums[a + 2] + nums[a + 3] > target:
break
# Array maximum and less than target, traversal next
if nums[a] + nums[n - 1] + nums[n - 2] + nums[n - 3] < target:
continue
for b in range(a + 1, n - 2):
# Prevent duplication
if b - a > 1 and nums[b] == nums[b - 1]:
continue
if nums[a] + nums[b] + nums[b + 1] + nums[b + 2] > target:
break
if nums[a] + nums[b] + nums[n - 1] + nums[n - 2] < target:
continue
# Double pointer
left = b + 1
right = n - 1
while left < right:
tmp = nums[a] + nums[b] + nums[left] + nums[right]
if tmp == target:
res.append([nums[a], nums[b], nums[left], nums[right]])
while left < right and nums[left] == nums[left+1]:
left += 1
while left < right and nums[right] == nums[right-1]:
right -= 1
left += 1
right -= 1
elif tmp > target:
right -= 1
else:
left += 1
return res
```  Published 23 original articles, won praise 5, visited 3297

Tags: less Python

Posted on Wed, 15 Jan 2020 07:15:33 -0500 by bigger