Has two solution, brute force and hash:
- Two for loop to find two numbers add equal target.
- Create a map, then traversed nums, if current
target - value
exist in map, return the index stored in the map and the current index, else store the current value as key, index as value and to map.
Solution time complexity is O
solution 1
func twoSum(nums []int, target int) []int {
for i := 0; i < len(nums); i++ {
for j := 1; j < len(nums); j++ {
if nums[i]+nums[j] == target && i != j {
return []int{i, j}
}
}
}
return nil
}
solution 2
func twoSum(nums []int, target int) []int {
hash := map[int]int{}
for index, value := range nums {
preindex, ok := hash[target-value]
if ok {
return []int{preindex, index}
} else {
hash[value] = index
}
}
return []int{}
}