Contents

[Golang][Leetcode][HashTable]刷題系列-1-Two Sum


這個學習紀錄的第一題就來經典又容易的Two Sum吧!


1. Two Sum


Level: Easy

原題連結: Click

題目:

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:

Note

Input: nums = [2,7,11,15], target = 9

Output: [0,1]

Output: Because nums[0] + nums[1] == 9, we return [0, 1].


以下是我自己的解法 - O(n)

Runtime: 4 ms, faster than 93.12% of Go online submissions for Two Sum.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
func twoSum(nums []int, target int) []int {
    
    m := make(map[int]int)
    
    for i := 0; i < len(nums); i++ {
        
        another := target - nums[i]
        
        if _, ok := m[another]; ok {
            
            return []int{m[another] , i}
        
        }
        
        m[nums[i]] = i
    }
    
    return nil
}


最後祝福努力認真的各位 “All your dream of are hidden in your daily life” 我們峰頂見!!!