Short C++ and Java solution


  • 0

    The idea is to sort the array then concatenate them. The key part is how to sort? We compare 2 strings s1, s2 by their concatenations: s1+s1 and s2+s1.

    C++:

    string largestNumber(vector<int>& nums) {
        int max = 0, n = nums.size();
        string R = "";
        vector<string> V;
        for (int i=0; i<n; i++) {
            if (max<nums[i]) max = nums[i];
            V.push_back(to_string(nums[i]));
        }
        sort(V.begin(), V.end(), [](string &s1, string &s2){ return s1+s2>s2+s1; });
        for (int i=0; i<n; i++) R += V[i];
        return max==0? "0":R;
    }
    

    Java:

    public String largestNumber(int[] nums) {
        int max = 0;
        String R = "";
        String[] V = new String[nums.length];
        for (int i=0; i<nums.length; i++) {
            if (max<nums[i]) max = nums[i];
            V[i] = nums[i] + "";
        }
        Comparator<String> comp = new Comparator<String>() {
            public int compare(String s1, String s2){
                return (s2+s1).compareTo(s1+s2);
            }
        };
        Arrays.sort(V, comp);
        for (int i=0; i<nums.length; i++) R += V[i];
        return max==0? "0":R;
    }

Log in to reply
 

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