美文网首页
LeetCode之3Sum(Kotlin)

LeetCode之3Sum(Kotlin)

作者: 糕冷羊 | 来源:发表于2021-07-14 13:47 被阅读0次

问题:



方法:
暴力解法可以通过三层循环,但是复杂度会达到三阶;通过生成map可以减少一次循环次数,然后进行两层循环即可以获得最终结果。

package com.eric.leetcode

class ThreeSum {
    fun threeSum(nums: IntArray): List<List<Int>> {
        val xSet = nums.mapIndexed { index, it -> it to index }.toMap().toMutableMap()
        val result = mutableSetOf<List<Int>>()
        for (i in 0..nums.lastIndex) {
            for (j in i..nums.lastIndex) {
                val x = nums[i]
                val y = nums[j]
                if (xSet.containsKey(-x - y)) {
                    val k = xSet[-x - y]
                    if (i != j && i != k && k != j) {
                        result.add(listOf(x, y, -x - y).sorted())
                    }
                }
            }
        }
        return result.toList()
    }
}

fun main() {
    val input = intArrayOf(-1, 0, 1, 2, -1, -4)
    val threeSum = ThreeSum()
    threeSum.threeSum(input)
}

有问题随时沟通

具体代码实现可以参考Github

相关文章

网友评论

      本文标题:LeetCode之3Sum(Kotlin)

      本文链接:https://www.haomeiwen.com/subject/xijypltx.html