1.两数之和

Go

战胜95.74%的Go提交

1
2
3
4
5
6
7
8
9
10
11
12
func twoSum(nums []int, target int) []int {
m := map[int]int{}
var ls int
for i := range nums {
ls = m[nums[i]]
if ls != 0 {
return []int{ls - 1, i}
}
m[target - nums[i]] = i + 1
}
return nil;
}

Java

战胜12.64%的Java提交

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