[Go] LeetCode 1. Two Sum
1 min readJan 16, 2020
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.