1. Sum of two numbers

Title description:

Given an integer array nums and an integer target value target, find the two integers in the array and the target values and return their array subscripts.

You can assume that there is only one answer for each type of input. However, the same element in the array cannot be repeated in the answer.

You can return the answers in any order.

Example 1:
Input: nums = [2,7,11,15], target = 9 output: [0,1]Copy the code
Example 2:
Input: nums = [3,2,4], target = 6Copy the code
Example 3:
Input: nums = [3,3], target = 6Copy the code
Limitations:
2 <= nums.length <= 103-109 <= nums[I] <= 109-109 <= target <= 109Copy the code

Directions: For this part,

So first of all, let’s look at the requirements of this problem. It’s easy to understand. Check to see if the sum of two numbers in the array is the target number, and return the subscripts of both numbers if so. Here are two ways to solve the problem:

Hash table syntax: hash table syntax is easy to understand. All we need to do is use a hashMap to store the iterated element and its corresponding index. Each time you iterate over an element, see if there is a target number in the hashMap that meets the problem’s requirements. It’s not hard to see that it only takes one walk to complete our problem, essentially trading space for time.

Hash table solution to achieve:

func twoSum(nums []int, target int) []int {
	prevNums := map[int]int{}
	for i, num := range nums {
		targetNum := target - num
		targetNumIndex, ok := prevNums[targetNum]
		if ok {
			return []int{targetNumIndex, i}
		} else {
			prevNums[num] = i
		}
	}
	return []int{}
}
Copy the code

Brute force cracking solution to achieve:

func twoSum(nums []int, target int) []int {
     nL := len(nums)
     for idx,v := range nums {
       for idx2 := idx + 1; idx2 < nL; idx2 ++ {
           if (v + nums[idx2]) == target {
                return []int{idx,idx2}
             }
         }
     }
     return nil
}
Copy the code

Conclusion:

In addition to the sum of two numbers, similar sum problems are 15. Sum of three numbers and 18. The sum of four numbers and the sum of three numbers are different from the sum of two numbers. The problem is to return all the cases, so the key core of the problem is to remove the repeated cases, and interested friends can try to draw inferences.