Golang Foundation
Acknowledgement: LeetCode-In-Go
1. Two Sum
subject
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
Solution 1 Violent Solution
Solving problems
Main ideas:
- Traverse through all items
- The inner traversal starts after the current term and adds it to the current term to calculate the result.
- Returns if it is equal to target
Specific implementation code:
// Basic solution to violence. func twoSum(nums []int, target int) []int { for i := 0; i < len(nums); i++ { for j := i + 1; j < len(nums); j++ { if (nums[i] + nums[j] == target) { return []int{i, j} } } } return nil }
Solution 2 Query the difference serial number
Solving problems
a + b = target
It can also be regarded as yes.
a = target - b
In the ordinal number of map [integer] integers, the ordinal number of a can be queried. This eliminates the need to nest two for loops.
// The Solution Using map func twoSum(nums []int, target int) []int { index := make(map[int]int, len(nums)) // Obtain the ordinal number of b through the for loop for i, b := range nums { // Get the serial number of a = target - b by querying the serial number if j, ok := index[target - b]; ok { // When ok is true, then the corresponding a = target - b. return []int{j, i} } // Save the values of b and i into the map index[b] = i } return nil }
Operating efficiency comparison:
Write test program
package problem0001 import ( "testing" "github.com/stretchr/testify/assert" ) type para struct { one []int two int } type ans struct { one []int } type question struct { p para a ans } func Test_OK(t *testing.T) { ast := assert.New(t) qs := []question{ question{ p: para{ one: []int{3, 2, 4}, two: 6, }, a: ans{ one: []int{1, 2}, }, }, question{ p: para{ one: []int{3, 2, 4}, two: 8, }, a: ans{ one: nil, }, }, } for _, q := range qs { a, p := q.a, q.p ast.Equal(a.one, twoSum(p.one, p.two), "input:%v", p) } }