Golang solution example, takes 12ms


  • 1
    func twoSum(nums []int, target int) []int {
        mp := make(map[int]int) // key: number, val: index in nums
        
        for i, num := range(nums) {
            if idx, ok := mp[target - num]; ok {
                return []int{idx, i}
            }
            mp[num] = i
        }
        return nil // just to avoid a compile error
    }
    

    A simple solution that uses map to hold an index of each integer's occurrence.
    Time complexity: O(N)
    Space complexity: O(N)
    While N is a length of nums.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.