1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| object ThreeNumSum {
def main(args: Array[String]): Unit = { println(solution1(Array(-1, 0, 1, 2, -1, -4))) println(solution2(Array(-1, 0, 1, 2, -1, -4))) println(solution2(Array(0, 0, 0))) }
def solution1(nums: Array[Int]): List[List[Int]] = { val set = scala.collection.mutable.Set[List[Int]]() for (i <- 0 until nums.length) { for (j <- i + 1 until nums.length) { for (k <- j + 1 until nums.length) { if (nums(i) + nums(j) + nums(k) == 0) { set += List(nums(i), nums(j), nums(k)).sortWith((a, b) => if (a - b < 0) true else false) } } } } set.toList }
def solution2(nums: Array[Int]): List[List[Int]] = { val set = scala.collection.mutable.Set[List[Int]]() util.Arrays.sort(nums)
if (nums.length == 3 && nums(0) + nums(1) + nums(2) == 0) { return List(nums.toList) }
for (i <- 0 until nums.length - 3) { var l = i + 1 var r = nums.length - 1 while (l < r) { if (nums(l) + nums(r) > 0 - nums(i)) { r -= 1 } else if (nums(l) + nums(r) < 0 - nums(i)) { l += 1 } else if (l != r) { set += List(nums(i), nums(l), nums(r)).sortWith((a, b) => if (a - b < 0) true else false) l += 1 } } }
set.toList } }
|