Skip to content

Commit 4be4cd0

Browse files
committed
problem: four sum
1 parent 10d5f2e commit 4be4cd0

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

problem48/main.dart

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
2+
void main(List<String> args) {
3+
print(fourSum([1,0,-1,0,-2,2],0));
4+
print(fourSum([2,2,2,2,2], 8));
5+
}
6+
List<List<int>> fourSum(List<int> nums, int target) {
7+
nums.sort();
8+
List<List<int>> result = [];
9+
for (int i = 0; i < nums.length - 3; i++) {
10+
if (i > 0 && nums[i] == nums[i - 1]) continue;
11+
for (int j = i + 1; j < nums.length - 2; j++) {
12+
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
13+
int left = j + 1, right = nums.length - 1;
14+
while (left < right) {
15+
int sum = nums[i] + nums[j] + nums[left] + nums[right];
16+
if (sum == target) {
17+
result.add([nums[i], nums[j], nums[left], nums[right]]);
18+
left++;
19+
right--;
20+
while (left < right && nums[left] == nums[left + 1]) left++;
21+
while (left < right && nums[right] == nums[right - 1]) right--;
22+
} else if (sum < target) {
23+
left++;
24+
} else {
25+
right--;
26+
}
27+
}
28+
}
29+
}
30+
return result;
31+
}

0 commit comments

Comments
 (0)