File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* *
2
+ * Created by VINAY on 11-08-2024.
3
+ * Github:@vinayByte
4
+ *
5
+ */
6
+ // O(n^2)
7
+ fun threeSum (nums : IntArray ): List <List <Int >> {
8
+ val result = mutableSetOf<List <Int >>()
9
+ val n = nums.size
10
+ val sortedNums = nums.sorted()
11
+ for (i in 0 until n) {
12
+ var left = i + 1
13
+ var right = n - 1
14
+ while (left < right) {
15
+ var sum = sortedNums[i] + sortedNums[left] + sortedNums[right]
16
+ if (sum == 0 ) {
17
+ val triplet = listOf (sortedNums[i], sortedNums[left], sortedNums[right])
18
+ result.add(triplet)
19
+ left++
20
+ right--
21
+ } else if (sum < 0 ) {
22
+ left++
23
+ } else {
24
+ right--
25
+ }
26
+ }
27
+ }
28
+
29
+ return result.toList()
30
+ }
31
+
32
+ // Brute Force: O(n3)
33
+ fun threeSum1 (nums : IntArray ): List <List <Int >> {
34
+ val result = mutableSetOf<List <Int >>()
35
+ val n = nums.size
36
+
37
+ for (i in 0 until n) {
38
+ for (j in i + 1 until n) {
39
+ for (k in j + 1 until n) {
40
+ if ((nums[i] + nums[j] + nums[k] == 0 ) && (i != j && i != k && j != k)) {
41
+ val triplet = listOf (nums[i], nums[j], nums[k]).sorted()
42
+ result.add(triplet)
43
+ }
44
+ }
45
+ }
46
+ }
47
+ return result.toList()
48
+ }
You can’t perform that action at this time.
0 commit comments