Scala Solution


  • 0
    R
    case class Quad(a: Int, b: Int, c: Int, d: Int)
    def fourSum(values: Array[Int], target: Int) : List[Quad] = {
        val sorted = values.sortBy(x => x) // sort ascending
        val n = values.size
        val result = ListBuffer.empty[Quad]
        for (i <- 0 to n - 4){
          var j = i + 1
          while (j <= n - 3){
            var k = j + 1
            while (k <= n - 2) {
              val sum = sorted(i) + sorted(j) + sorted(k)
              val desired = target - sum
              var l = k + 1
              while (l <= n - 1 && sorted(l) <= desired){
                if (sorted(l) == desired){
                  result += Quad(sorted(i), sorted(j), sorted(k), sorted(l))
                }
                l = l + 1
              }
            k = k + 1
            }
           j = j + 1
          }
        }
        result.toList
      }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.