mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
修正0001.两数之和dart
- 儘量給定類型 - 使用HashMap取代不適合的List
This commit is contained in:
@ -402,16 +402,18 @@ public class Solution {
|
||||
### Dart:
|
||||
|
||||
```dart
|
||||
List<int> twoSum(List<int> nums, int target) {
|
||||
var tmp = [];
|
||||
for (var i = 0; i < nums.length; i++) {
|
||||
var rest = target - nums[i];
|
||||
if(tmp.contains(rest)){
|
||||
return [tmp.indexOf(rest), i];
|
||||
}
|
||||
tmp.add(nums[i]);
|
||||
import 'dart:collection';
|
||||
|
||||
List<int> twoSum(List<int> nums, int target) {
|
||||
HashMap<int, int> hashMap = HashMap();
|
||||
for (int i = 0; i < nums.length; i++) {
|
||||
int rest = target - nums[i];
|
||||
if (hashMap.containsKey(rest)) {
|
||||
return [hashMap[rest]!, i];
|
||||
}
|
||||
return [0 , 0];
|
||||
hashMap.addEntries({nums[i]: i}.entries);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user