Scala solution in one line


  • 0
    B
    object Solution {
        def largestNumber(nums: Array[Int]): String = {
            nums.map(_.toString).sortWith((s1, s2) => (s2 + s1) < (s1 + s2)).reduce( (s1, s2) => s1 match {
                case "0" => s2
                case _ => s1 + s2
            })
        }
    }
    

  • 0
    B

    Added handing corner cases, seems a little bit ugly now :-(

    def largestNumber(optNums: Option[Array[Int]]): String = {
        optNums match{
          case Some(nums) => nums.size match {
            case 0 => ""
            case _ => { 
              nums.map(_.toString).sortWith( (x,y) => (y + x) < (x + y)).reduce(
                (e1, e2) => e1 match {
                  case "0" => e2
                  case _ => e1 + e2}
              )}
          }
          case _ => ""
        }
      }
    

Log in to reply
 

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