Preface【目录】
This bolg will witness at least 100 Go-solutions for Leetcode , which a freshman tries to update.
本博客会发布100篇Leetcode题目的Go语言解法,新人不定期更新。
So there may be many mistakes in the blogs below, please exceuse me if you find some bugs in my grammar or program.
英文语法或代码有误还望见谅。
Ⅰ. Today’s challenge【今日挑战】
- 1. Two Sum【求两数和】
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Ⅱ. Solution【题解】
1. Ideas【思路】
-
Brute Force【暴力法】
Tranvers the array. We should findtaeget-x
ifx
is the number which we found in this iteration.
遍历数组,将数组中每一个x
进行遍历,然后找到taeget-x
即可。 -
Hash Table【哈希表】
It’s a typical algorithm that we trade time for space.HashTable
is a blade whose time complexity isO(1)
. We can get index oftaeget-x
byHashTable[taeget-x]
if numberx
is in our hand.
一个用空间换时间的典型例子,哈希表HashTable
差找的复杂度为O(1)
。在从第一个数组元素开始遍历的时候逐渐构建HashTable
,之后一旦需要taeget-x
,只需要HashTable[taeget-x]
即可查到其索引。
2. Code【代码】
//Idea one: Brute Force【暴力法】
func twoSum(nums []int, target int) []int {
length := len(nums)
// Using `range` can simplify our code
//for i := 0; i < length; i++ {
for i, total := range nums {
fmt.Printf("%d,%d", i, total)
//var total = nums[i]
for j := i + 1; j < length; j++ {
if total+nums[j] == target {
return []int{i, j}
}
}
}
return nil
}
//Idea Two: Hash Table【哈希表】
func twoSumUlt(nums []int, target int) []int {
hashTable := map[int]int{}
for i, num := range nums {
if j, found := hashTable[target-num]; found {
return []int{i, j}
}
hashTable[num] = i
}
return nil
}
Summary【小结】
It’s my first time trying use English to write a blog. Although the challenge is ‘‘No.1 Two Sum’’ in Leetcode, I have to strugle to do it. Keep Going
!
第一次尝试用英语写博客,随便找了一个Leetcode第一题来练手,确实有点吃力,慢慢坚持下去吧!