LeetCode Largest Number 贪心

来源:互联网 发布:域名要备案才能解析吗 编辑:程序博客网 时间:2024/05/16 11:00

将数组中的元素进行重排,组成最大的数。

如果只有两个数,可以简单判断:,使用贪心,将数组中的元素按照上述比较规则进行降序排序,进行拼接即为所求。证明如下:

假设按照贪心得到的最优解为:(其中位,位,)。若存在解(交换位置)比更优。令右边有位,则有:,与假设矛盾。因此贪心为最优解。代码如下:

class Solution {public:    string largestNumber(vector<int>& nums) {        sort(nums.begin(), nums.end(), CMP());        if(nums[0] == 0)            return "0";        string ans = "";        int len = nums.size();        for(int i = 0; i < len; ++i){            ans += to_string(nums[i]);        }        return ans;    }private:    struct CMP{        bool operator()(const int& a, const int& b){            long long ans1 = 10, ans2 = 10;            int n1 = a / 10, n2 = b / 10;            while(n1)                ans1 *= 10, n1 /= 10;            while(n2)                ans2 *= 10, n2 /= 10;            return ans2 * a + b > ans1 * b + a;        }    };};


0 0
原创粉丝点击