[Go] LeetCode 1. Two Sum

Description

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solution

/* [Go]  1.Brute Force O(n2) */
func twoSum(nums []int, target int) []int {
for i := 0; i < len(nums); i++{
for j := i + 1; j < len(nums); j++{
if nums[j] == target - nums[i]{
return []int{i,j}
}
}
}
return nil
}
/* [Go] 2. Two-pass Hash Table O(n) point: using complement*/
func twoSum(nums []int, target int) []int {
indexMap := make(map[int]int)
for i := 0; i < len(nums); i++ {
indexMap[nums[i]] = i
}
for i := 0; i < len(nums); i++ {
complement := target - nums[i]
if _,ok := indexMap[complement]; ok && indexMap[complement] != i{
return []int{i,indexMap[complement]}
}
}
return nil
}
/* [Go] 3. One-pass Hash Table O(n) point: using complement*/
func twoSum(nums []int, target int) []int{
indexMap := make(map[int]int)
for i := 0; i < len(nums); i++ {
complement := target - nums[i]
if _,ok := indexMap[complement]; ok {
return []int{i,indexMap[complement]}
}
indexMap[nums[i]] = i
}
return nil
}

I want to write the test code later.

--

--

--

Site Reliablity Engineer in Tokyo. SRE/devops/Go/AWS/Terraform/Kubernetes/Docker

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
TAKASHI NARIKAWA

TAKASHI NARIKAWA

Site Reliablity Engineer in Tokyo. SRE/devops/Go/AWS/Terraform/Kubernetes/Docker

More from Medium

Concurrency in Golang, Goroutines, and Channels Explained

How To Begin With Golang | Part 3

Bubble Sort in Go

Generating JSON data from Go (Golang) structs with Go2JSON