Programming languages are written for computers, which must have something in common with human languages and will be an essential skill for future life.

A few key points to learn a skill quickly:

  1. Clear goals: practical drives.
  2. Get quick feedback: Know what you’re doing right or wrong and correct it.
  3. Create deep understanding: Be able to use or explain.
  4. Intensive learning: deliberate practice versus extensive practice.

Learning a language has the following characteristics:

  1. Clear, clear and unambiguous questions about achieving goals.
  2. Online or local compiler, clear compilation errors or test case errors, easy to correct syntax, program logic errors in time.
  3. Questions are usually difficult and require deep understanding.
  4. It’s worth doing this exercise. Just thinking exercises have a lot of benefits.

Of course, it’s worth going over the basic syntax of Go before you brush through the questions.

Start with the simplest question:

1. Sum of two numbers

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.

Source: LeetCode link: leetcode-cn.com/problems/tw… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Use the mapping table (value -> index) to quickly find if there is a target value.

My Go first execution: of course the compilation did not pass O (╥﹏╥) O

func twoSum(nums []int, target int) []int {
    var numsMap map[int]int
    for i:=0; i <= len(nums); i++ {
        val, ok := numsMap[target - nums[i]]
        if (ok) {
            return {i, val}
        }
        numsMap[nums[i]] = i
    }
    return nil
}
Copy the code

There are a few mistakes:

  1. Go map can be used only after it is initialized

  2. The returned array cannot be written this way

    {i, val}
    Copy the code
  3. Of course, there’s a lot of debate about whether to return nil or an empty array

Fixed code:

func twoSum(nums []int, target int) []int {
    numsMap := make(map[int]int)
    for i:=0; i <= len(nums); i++ {
        val, ok := numsMap[target - nums[i]]
        if (ok) {
            return []int{i, val}
        }
        numsMap[nums[i]] = i
    }
    return nil
}
Copy the code

Further, after using range’s syntax modification:

func twoSum(nums []int, target int) []int {
    numsMap := make(map[int]int)
    for index, value := range nums {
        val, ok := numsMap[target - value]
        if (ok) {
            return []int{index, val}
        }
        numsMap[nums[index]] = index
    }
    return nil
}
Copy the code

Knowledge of Go: array, set map, range, nil, etc.