Quick_sort with self-defined compare function, running 13 ms, C++


  • 0
    P
    class Compare{
    public:
    	bool operator()(string s1, string s2)
    	{
    		return s1 + s2 < s2 + s1;
    	}
    };
    
    class Solution {
    public:
    	string largestNumber(vector<int> &num) {
    		int i;
    		for (i = 0; i < num.size(); i++)
    			if (num[i] != 0)
    				break;
    		if (i == num.size()) // All numbers are 0
    			return "0";
    		vector<string> v;
    		for (i = 0; i < num.size(); i++)
    			v.push_back(to_string(num[i]));
    		sort(v.begin(), v.end(), Compare());
    		string result;
    		for (i = v.size() - 1; i >= 0; i--)
    			result += v[i];
    		return result;
    	}
    };

Log in to reply
 

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