Skip to content

Instantly share code, notes, and snippets.

@ervinod
Last active August 1, 2023 15:18
Show Gist options
  • Select an option

  • Save ervinod/345ae3f083e5e7ac4a28eb27555cbad0 to your computer and use it in GitHub Desktop.

Select an option

Save ervinod/345ae3f083e5e7ac4a28eb27555cbad0 to your computer and use it in GitHub Desktop.
problem-1

problem-1

Given nums = [2, 7, 11, 15], target = 18. The output should be [1, 2]. Because nums[1] + nums[2] = 7 + 11 = 18.

Created with <3 with dartpad.dev.

import 'dart:math';
void main() {
//Given nums = [2, 7, 11, 15], target = 18.
//The output should be [1, 2].
//Because nums[1] + nums[2] = 7 + 11 = 18.
final nums = [2, 7, 11, 15];
int target = 18;
final result = getResultWay1(nums, target);
//final result = getResultWay2(nums, target);
print(result);
}
List<int> getResultWay1(List<int> nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return [i, j];
}
}
}
return [];
}
List<int> getResultWay2(List<int> nums, int target) {
var map = <int, int>{};
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
final elem =
map.entries.firstWhere((element) => element.key == complement);
return [elem.value, i];
} else {
map.putIfAbsent(nums[i], () => i);
}
}
return [];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment