Ruby 5 lines solution.


  • 0
    L

    It is my first time to use Ruby to write something. Any suggestion is welcomed.

    def largest_number(nums)
        copy = nums.sort! {|a, b| b.to_s+a.to_s <=> a.to_s+b.to_s}
        if copy[0] == 0
             return "0"
        end    
        copy.join('')
    

    end


  • 1

    Your five lines in one :-P

    def largest_number(nums)
        nums.map(&:to_s).sort { |a, b| b + a <=> a + b }.join.to_i.to_s
    end
    

    Or:

    def largest_number(nums)
        nums.sort { |a, b| "#{b}#{a}" <=> "#{a}#{b}" }.join.to_i.to_s
    end
    

    Btw, copy = nums.sort!... doesn't make sense. After that line, copy and nums refer to the exact same object. So you could just work with nums. If you were trying to keep nums intact (not sort it), you should remove the !.


  • 0
    L

    Wow, it is amazing. Your code is very beautiful and I learn a lot from it.


  • 0

    I wrote a few more now, in case you're interested.


  • 0
    L

    Thanks a lot. I have read the thread. It helps me a lot.
    By the way, I want to reverse traverse a 2D array, is there any easy way?


  • 0

    Here's one way:

    irb(main):047:0> matrix = [[1,2,3], [4,5,6], [7,8,9]]
    => [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    irb(main):048:0> matrix.reverse_each { |row| row.reverse_each { |c| p c } }
    9
    8
    7
    6
    5
    4
    3
    2
    1
    => [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    irb(main):049:0>

  • 0
    L

    Thanks for your detailed explanation.


Log in to reply
 

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