Short 32ms C++ solution using lexicographic comparison


  • 14
    D

    Given two numbers, we want to know which one should go first to create the lexicographically greater string. So we sort the numbers based on this rule.

    class Solution {
    public:
        string largestNumber(vector<int>& nums) {
            string result;
            sort(nums.begin(), nums.end(), [](int a, int b) { return to_string(a) + to_string(b) > to_string(b) + to_string(a); });
            for (int n : nums) { result += to_string(n); }
            return result.front() == '0' ? "0" : result;
        }
    };

  • 0
    S
    This post is deleted!

Log in to reply
 

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