您的位置:首页 > 其它

LeetCode 179. Largest Number

2016-07-16 13:23 155 查看
Problem: https://leetcode.com/problems/largest-number/

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.

Thought:

1. turn all int into str, then compare next_now+numStr[i] and numStr[i] + next_now to find the next_now, next_now is the next one to append to the result string, this method is O(n2), only beats 5% cpp submissions

2.sort the numStr with a function, the append them one by one reference: https://discuss.leetcode.com/topic/7286/a-simple-c-solution/2

Code C++ thought 1:

class Solution {
public:
string largestNumber(vector<int>& nums) {
vector<string> numStr;
for (int i = 0; i < nums.size(); i++) {
numStr.push_back(to_string(nums[i]));
}

string solve = "";
while (numStr.size() > 1) {
vector<string>::iterator next = findNext(numStr);
solve += *next;
numStr.erase(next);
}
solve += numStr[0];

if (solve[0] == '0') {
return "0";
}
return solve;
}

vector<string>::iterator findNext(vector<string>& nums) {
int next = 0;
for (int i = 1; i < nums.size(); i++) {
string a,b;
a = nums[next] + nums[i];
b = nums[i] + nums[next];
next = a > b ? next : i;
if (a == b) {
next = nums[next].length() <= nums[i].length() ? next : i;
}
}
return nums.begin() + next;
}

};


Code C++ thought 2:

class Solution {
public:
string largestNumber(vector<int> &num) {
vector<string> numStr;
for (int i = 0; i < num.size(); i++) {
numStr.push_back(to_string(num[i]));
}

string solve = "";
sort(numStr.begin(), numStr.end(), [](string &s1, string &s2){return s1 + s2 > s2 + s1;});
for (int i = 0; i < numStr.size(); i++) {
solve += numStr[i];
}
if (solve[0] == '0') {
return "0";
}

return solve;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: