【LeetCode】1. 两数之和(gloang)

第一个种解法 暴力判断 耗时较久

package main

import "fmt"

func main() {
	results := twoSum([]int{2, 7, 11, 15}, 9)
	fmt.Println(results)
}

func twoSum(nums []int, target int) []int {
	length := len(nums)
	for i := 0; i < length; i++ {
		for j := i + 1; j < length; j++ {
			if nums[i]+nums[j] == target {
				return []int{i, j}
			}
		}
	}
	return []int{}
}

第二种解法 哈希 用时较少

package main

import "fmt"

func main() {
	results := twoSum([]int{3, 2, 4}, 6)
	fmt.Println(results)
}

func twoSum(nums []int, target int) []int {
	cache := map[int]int{}
	for key, value := range nums {
		cache[value] = key
	}
	length := len(nums)
	for i := 0; i < length; i++ {
		value := target - nums[i]
		key, ok := cache[value]
		if ok == true && key != i {
			return []int{i, key}
		}
	}
	return []int{}
}

你可能感兴趣的:(leetcode,golang,两数之和)