All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0001_0100.s0015_3sum.Solution.kt Maven / Gradle / Ivy

There is a newer version: 1.30
Show newest version
package g0001_0100.s0015_3sum

// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Array #Sorting #Two_Pointers
// #Data_Structure_II_Day_1_Array #Algorithm_II_Day_3_Two_Pointers #Udemy_Two_Pointers
// #2022_10_06_Time_761_ms_(90.55%)_Space_77.7_MB_(83.71%)

import kotlin.collections.ArrayList

class Solution {
    fun threeSum(nums: IntArray): List> {
        nums.sort()
        val len = nums.size
        val result: MutableList> = ArrayList()
        var l: Int
        var r: Int
        var i = 0
        while (i < len - 2) {
            l = i + 1
            r = len - 1
            while (r > l) {
                val sum = nums[i] + nums[l] + nums[r]
                if (sum < 0) {
                    l++
                } else if (sum > 0) {
                    r--
                } else {
                    val list: MutableList = ArrayList()
                    list.add(nums[i])
                    list.add(nums[l])
                    list.add(nums[r])
                    result.add(list)
                    while (l < r && nums[l + 1] == nums[l]) {
                        l++
                    }
                    while (r > l && nums[r - 1] == nums[r]) {
                        r--
                    }
                    l++
                    r--
                }
            }
            while (i < len - 1 && nums[i + 1] == nums[i]) {
                i++
            }
            i++
        }
        return result
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy