[Leetcode X Golang] Study Note 01


By: Axe 2019-10-01

Motivation

When I was talking with my wife on the phone about probability to start a new life in another city in U.S or some other big city like Vancouver or Toronto in Canada. She told me only if I find a job at companies like Google or Amazon, then we could move. Well, fine, time to prove myself then. As everyone knows, to get into those companies, there is only one way, pass the algorithm test. From what I learnt from my past failed google and amazon interview lessens, I better to practice more questions on leetcode this time before actually go on an interview. Here we go.

Why Go

Simply because I recently learnt it and need more practice. Therefore code in this series may not have very good quality, welcome to point out where I can improve them.

How

I will go through as many question as I can from first one in order this time. For each question I will read the description then go find the solution directly. This is the most efficient way to see more questions I believe. After I understand the solution I will just simply write it down in go and paste it here along the link of the solution I found. I will also write down the process of writing these code like what I searched and learnt, mostly in the code comments. By the way I usually don't write comments during coding, because I believe good readable code should show the logic clearly by look at the code itself. Alright, enough bullshit, let's get started.

Problem: 1. Two Sum

Solution: 中文 English

Code:

func twoSum(nums []int, target int) []int {
	var visited = make(map[int]int)
	for i, n := range nums {
		var diff = target - n
		if v, ok := visited[diff]; ok {
			return []int{v, i}
		}
		visited[n] = i
	}

	return []int{}
}

Note

  • to create a new map in go, we need use make()
  • to check if a key exists in map: if v, ok := visited[diff]; ok { // ... }
  • []int is a slice but [{len}]int is a array
  • go require to have a return if a return type is declared.