当前位置:网站首页>179. Maximum number - sort

179. Maximum number - sort

2022-07-05 01:42:00 The_ Dan

Given a set of nonnegative integers nums, Rearrange the order of each number ( Each number cannot be split ) Make it the largest integer .

Be careful : The output can be very large , So you need to return a string instead of an integer .
Example 1:
Input :nums = [10,2]
Output :“210”

Example 2:
Input :nums = [3,30,34,5,9]
Output :“9534330”

Example 3:
Input :nums = [1]
Output :“1”

Example 4:
Input :nums = [10]
Output :“10”

Nature is n Order of elements , As for which one comes first , Which one is in the back , Just add the character form to compare , for example "3"+“30" And "30”+"3" Compare , It can be concluded that 3 Put it in front .

class Solution {
    
public:
    string largestNumber(vector<int>& nums) {
    
        vector<string> vecStr;
        for(auto num : nums){
    
            vecStr.push_back(to_string(num));
        }
        for(auto i = 0; i != vecStr.size(); ++i){
    
            for(auto j = i + 1; j != vecStr.size(); ++j){
    
                string str1 = vecStr[i] + vecStr[j], str2 = vecStr[j] + vecStr[i];
                if(str1 < str2)
                    swap(vecStr[i], vecStr[j]);
            }
        }
        string ans;
        for(auto str : vecStr)
            ans += str;
        if(ans[0] == '0')   // Exists in the sample [0,0] The situation of , In this way, we will output "00", It should be "0"
            return "0";
        return ans;
    }
};

Accepted
230/230 cases passed (12 ms)
Your runtime beats 36.26 % of cpp submissions
Your memory usage beats 27.96 % of cpp submissions (11.1 MB)

原网站

版权声明
本文为[The_ Dan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141019324943.html