# 1. Two Sum

random-developer·2022년 12월 22일
0

## leet

목록 보기
1/1

Num: 7

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

void main() {
final s = Solution();
// final res1 = s.twoSum([2, 7, 11, 15], 9);
// print(res1);
// final res2 = s.twoSum([3, 2, 4], 6);
// print(res2);
// final res3 = s.twoSum([3, 3], 6);
// print(res3);
//
// final res21 = s.twoSum2([2, 7, 11, 15], 9);
// print(res21);
// final res22 = s.twoSum2([3, 2, 4], 6);
// print(res22);
// final res23 = s.twoSum2([3, 3], 6);
// print(res23);

final res31 = s.twoSum3([2, 7, 11, 15], 9);
print(res31);
final res32 = s.twoSum3([3, 2, 4], 6);
print(res32);
final res33 = s.twoSum3([3, 3], 6);
print(res33);

}

class Solution {

List<int> twoSum4(List<int> nums, int target) {
final myMap = {};
for (int i = 0; i < nums.length; i++) {
if (myMap.containsKey(target - nums[i]) && myMap[target - nums[i]] != i) {
return [i, myMap[target - nums[i]]];
}
myMap[nums[i]] = i;
}

return [];

}

List<int> twoSum3(List<int> nums, int target) {
final myMap = {};
for (int i = 0; i < nums.length; i++) {
myMap[nums[i]] = i;
}

for (int i = 0; i < nums.length - 1; i++) {
if (myMap.containsKey(target - nums[i]) && myMap[target - nums[i]] != i) {
return [i, myMap[target - nums[i]]];
}
}

return [];
}

List<int> twoSum2(List<int> nums, int target) {
for (int i = 0; i < nums.length - 1; i++) {
int pair = target - nums[i];
if (nums.contains(pair)) {
int pairIdx = nums.indexOf(pair, i + 1);
if (pairIdx == -1) {
continue;
}

if (pairIdx != i) {
return [i, pairIdx];
}

}
}
return [];
}

List<int> twoSum(List<int> nums, int target) {

for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return [i, j];
}
}

}
return [];
}
}
getRandomDeveloper()