LeetCode No.1 [Two Sum]

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:

1
2
3
4
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Leet Code Link


最简单的遍历实现

用最简单的遍历来实现,至于性能么只能呵呵了。
不过golang性能上差不多比C#快了10倍, 差距还是有点明显的。

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Solution {
public int[] TwoSum(int[] nums, int target)
{
for (int i = 0; i < nums.Length; i++)
{
for (int j = i + 1; j < nums.Length; j++)
{
if (nums[i] + nums[j] == target)
return new int[2] { i, j };
}
}
return null;
}
}

golang

1
2
3
4
5
6
7
8
9
10
func twoSum(nums []int, target int) []int {
for i := 0; i < len(nums); i++ {
for j := i + 1; j < len(nums); j++ {
if nums[i]+nums[j] == target {
return []int{i, j}
}
}
}
return nil
}


使用MAP优化性能

同样使用遍历, 但使用MAP存储遍历过的值, 新遍历的值通过MAP来查找相匹配的值, 这样只使用一个MAP分别优化了查找和存储的过程,大大优化了性能。
PS:预先为MAP定义空间进一步提升性能。
PPS: 如果数值中有重复的数字, 该逻辑不可用。

golang

1
2
3
4
5
6
7
8
9
10
11
12
func twoSum(nums []int, target int) []int {
l := len(nums)
dic := make(map[int]int, l)
for i := 0; i < l; i++ {
complement := target - nums[i]
if val, ok := dic[complement]; ok {
return []int{val, i}
}
dic[nums[i]] = i
}
return nil
}