Skip to content

Latest commit

 

History

History
41 lines (35 loc) · 890 Bytes

1.Two_sum.md

File metadata and controls

41 lines (35 loc) · 890 Bytes

Has two solution, brute force and hash:

  1. Two for loop to find two numbers add equal target.
  2. 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{}
}