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.
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 []; | |
| } |