Simple C++ solution with explaination[AC]


  • 0
    S

    Solution:

    If you look carefully, the result can be achieved by using sorting on strings with a little modification. We will create a custom sorting comparison function which will sort the array in the required format. We just now need to handle the case when there are 0's in the front.

    Code

    class Solution {
    private:
    static int cmp(string a, string b)
    {
        return a+b > b+a;
    }
    public:
        string largestNumber(vector<int>& nums) {
            
            vector<string> s;
            int len =0;
            string res = "";
            
            for(int i=0;i<nums.size();i++)
                s.push_back(to_string(nums[i]));
            
            sort(s.begin(), s.end(), cmp);
            
            for(int i=0;i<s.size();i++)
                 res += s[i];
            
            while(res[len]=='0')
                len++;
            
            res = res.erase(0, len);
            return (res.size()==0) ? "0" : res;
        }
    };
    

  • 0
    S

    #include <iostream>
    #include <string>
    #include <vector>
    #include <algorithm>
    using namespace std;

    // A comparison function which is used by sort() in printLargest()
    int myCompare(string X, string Y)
    {
    // first append Y at the end of X
    string XY = X.append(Y);

    // then append X at the end of Y
    string YX = Y.append(X);
    
    // Now see which of the two formed numbers is greater
    return XY.compare(YX) > 0 ? 1: 0;
    

    }

    // The main function that prints the arrangement with the largest value.
    // The function accepts a vector of strings
    void printLargest(vector<string> arr)
    {
    // Sort the numbers using library sort funtion. The function uses
    // our comparison function myCompare() to compare two strings.
    // See http://www.cplusplus.com/reference/algorithm/sort/ for details
    sort(arr.begin(), arr.end(), myCompare);

    for (int i=0; i < arr.size() ; i++ )
        cout << arr[i];
    

    }

    // driverr program to test above functions
    int main()
    {
    vector<string> arr;

    //output should be 6054854654
    arr.push_back("54");
    arr.push_back("546");
    arr.push_back("548");
    arr.push_back("60");
    printLargest(arr);
    

    return 0;
    }


Log in to reply
 

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