mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 02:53:31 +08:00
update 0001.两数之和:加注释,给java代码一点优化
This commit is contained in:
@ -134,12 +134,13 @@ public int[] twoSum(int[] nums, int target) {
|
|||||||
}
|
}
|
||||||
Map<Integer, Integer> map = new HashMap<>();
|
Map<Integer, Integer> map = new HashMap<>();
|
||||||
for(int i = 0; i < nums.length; i++){
|
for(int i = 0; i < nums.length; i++){
|
||||||
int temp = target - nums[i];
|
int temp = target - nums[i]; // 遍历当前元素,并在map中寻找是否有匹配的key
|
||||||
if(map.containsKey(temp)){
|
if(map.containsKey(temp)){
|
||||||
res[1] = i;
|
res[1] = i;
|
||||||
res[0] = map.get(temp);
|
res[0] = map.get(temp);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
map.put(nums[i], i);
|
map.put(nums[i], i); // 如果没找到匹配对,就把访问过的元素和下标加入到map中
|
||||||
}
|
}
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
@ -152,16 +153,17 @@ class Solution:
|
|||||||
def twoSum(self, nums: List[int], target: int) -> List[int]:
|
def twoSum(self, nums: List[int], target: int) -> List[int]:
|
||||||
records = dict()
|
records = dict()
|
||||||
|
|
||||||
for index, value in enumerate(nums):
|
for index, value in enumerate(nums):
|
||||||
if target - value in records:
|
if target - value in records: # 遍历当前元素,并在map中寻找是否有匹配的key
|
||||||
return [records[target- value], index]
|
return [records[target- value], index]
|
||||||
records[value] = index
|
records[value] = index # 遍历当前元素,并在map中寻找是否有匹配的key
|
||||||
return []
|
return []
|
||||||
```
|
```
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
|
// 暴力解法
|
||||||
func twoSum(nums []int, target int) []int {
|
func twoSum(nums []int, target int) []int {
|
||||||
for k1, _ := range nums {
|
for k1, _ := range nums {
|
||||||
for k2 := k1 + 1; k2 < len(nums); k2++ {
|
for k2 := k1 + 1; k2 < len(nums); k2++ {
|
||||||
@ -216,11 +218,11 @@ Javascript
|
|||||||
```javascript
|
```javascript
|
||||||
var twoSum = function (nums, target) {
|
var twoSum = function (nums, target) {
|
||||||
let hash = {};
|
let hash = {};
|
||||||
for (let i = 0; i < nums.length; i++) {
|
for (let i = 0; i < nums.length; i++) { // 遍历当前元素,并在map中寻找是否有匹配的key
|
||||||
if (hash[target - nums[i]] !== undefined) {
|
if (hash[target - nums[i]] !== undefined) {
|
||||||
return [i, hash[target - nums[i]]];
|
return [i, hash[target - nums[i]]];
|
||||||
}
|
}
|
||||||
hash[nums[i]] = i;
|
hash[nums[i]] = i; // 如果没找到匹配对,就把访问过的元素和下标加入到map中
|
||||||
}
|
}
|
||||||
return [];
|
return [];
|
||||||
};
|
};
|
||||||
|
Reference in New Issue
Block a user