mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +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<>();
|
||||
for(int i = 0; i < nums.length; i++){
|
||||
int temp = target - nums[i];
|
||||
int temp = target - nums[i]; // 遍历当前元素,并在map中寻找是否有匹配的key
|
||||
if(map.containsKey(temp)){
|
||||
res[1] = i;
|
||||
res[0] = map.get(temp);
|
||||
break;
|
||||
}
|
||||
map.put(nums[i], i);
|
||||
map.put(nums[i], i); // 如果没找到匹配对,就把访问过的元素和下标加入到map中
|
||||
}
|
||||
return res;
|
||||
}
|
||||
@ -152,16 +153,17 @@ class Solution:
|
||||
def twoSum(self, nums: List[int], target: int) -> List[int]:
|
||||
records = dict()
|
||||
|
||||
for index, value in enumerate(nums):
|
||||
if target - value in records:
|
||||
for index, value in enumerate(nums):
|
||||
if target - value in records: # 遍历当前元素,并在map中寻找是否有匹配的key
|
||||
return [records[target- value], index]
|
||||
records[value] = index
|
||||
records[value] = index # 遍历当前元素,并在map中寻找是否有匹配的key
|
||||
return []
|
||||
```
|
||||
|
||||
Go:
|
||||
|
||||
```go
|
||||
// 暴力解法
|
||||
func twoSum(nums []int, target int) []int {
|
||||
for k1, _ := range nums {
|
||||
for k2 := k1 + 1; k2 < len(nums); k2++ {
|
||||
@ -216,11 +218,11 @@ Javascript
|
||||
```javascript
|
||||
var twoSum = function (nums, target) {
|
||||
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) {
|
||||
return [i, hash[target - nums[i]]];
|
||||
}
|
||||
hash[nums[i]] = i;
|
||||
hash[nums[i]] = i; // 如果没找到匹配对,就把访问过的元素和下标加入到map中
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
Reference in New Issue
Block a user