好久没写博客,贡献一份高质量代码。高质量代码其实思路上没什么特别的,只是编程细节上面做了些优化。

        Your runtime beats 96.73% of cppsubmissions!

LargestNumber

Given a list of non negative integers, arrange them such that they form the largest number.

For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

Note: The result may be very large, so you need to return a string instead of an integer.

        使用贪心算法解决问题,重载sort函数,使用字符串比较实现高位比较,不多说,上代码。

static inline bool cpr(const string& s1, const string& s2){
	return s1 + s2 > s2 + s2;
}

class Solution {
public:
	string largestNumber(const vector<int>& nums) {
		stringstream ss;
		vector<string> numstr(nums.size());
		for (int i = 0; i < nums.size(); ++i){
			ss.clear();
			ss << nums[i];
			ss >> numstr[i];
		}
		sort(numstr.begin(), numstr.end(), cpr);
		
		string s;
		for (int i = 0; i < numstr.size(); ++i){
			s += numstr[i];
		}
		s.erase(0, s.find_first_not_of("0"));
		if(!s.length()){
		    s = "0";
		}
		return s;
	}

};

        OK,See You Next Chapter!

发表评论

邮箱地址不会被公开。 必填项已用*标注