Go | Two Sum【两数和】


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【思路】

  1. Brute Force【暴力法】
    Tranvers the array. We should find taeget-x if x is the number which we found in this iteration.
    遍历数组,将数组中每一个x进行遍历,然后找到taeget-x即可。

  2. Hash Table【哈希表】
    It’s a typical algorithm that we trade time for space. HashTable is a blade whose time complexity is O(1). We can get index of taeget-x by HashTable[taeget-x] if number x 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第一题来练手,确实有点吃力,慢慢坚持下去吧!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值