Skip to content
On this page

想法

首先我也是想的双循环,i和j的碰撞,所以我也是双循环写的

后面看了大神们的哈希表写法 捋通了但是还是有点不太理解

初步解题

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

我发现go必须在外面再写一个return

高级解法

看了看题解 果然牛逼 哈希表的写法

TS

ts
function handle(nums: number[], target: number): number[] {
  let map:Map<any,any> = new Map();
  for (let i = 0; i < nums.length; i++) {
    if (map.has(target - nums[i])) {
      return [map.get(target - nums[i]), i];
    }
    map.set(nums[i], i);
  }
  return [];
}

JS

js
function handle(nums, target) {
  let map = new Map();
  for (let i = 0; i < nums.length; i++) {
    if (map.has(target - nums[i])) {
      return [map.get(target - nums[i]), i];
    }
    map.set(nums[i], i);
  }
  return [];
}

GO

go
func twoSum(nums []int, target int) []int {
	hashTable := map[int]int{}
	for i, v := range nums {
		if p, ok := hashTable[target-v]; ok {
			return []int{p, i}
		}
		hashTable[v] = i
	}
	return nil
}