We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent df37585 commit d37a3a8Copy full SHA for d37a3a8
two-sum/sounmind.ts
@@ -0,0 +1,24 @@
1
+function twoSum(nums: number[], target: number): number[] {
2
+ // Pair each element with its index
3
+ const numsWithIndex = nums.map((value, index) => ({ value, index }));
4
+
5
+ // Sort the array based on the values
6
+ numsWithIndex.sort((a, b) => a.value - b.value);
7
8
+ let left = 0;
9
+ let right = numsWithIndex.length - 1;
10
11
+ while (left < right) {
12
+ const sum = numsWithIndex[left].value + numsWithIndex[right].value;
13
14
+ if (sum === target) {
15
+ return [numsWithIndex[left].index, numsWithIndex[right].index];
16
+ } else if (sum < target) {
17
+ left++;
18
+ } else {
19
+ right--;
20
+ }
21
22
23
+ return []; // In case there is no solution
24
+}
0 commit comments