解法1:sort()的比较函数用两个数的代数和比较,数较大时会产生类型溢出
class Solution {
#define base 10
static bool cmp(const int& a, const int& b)//需是static类型
{
int aBase = base, bBase = base;
while (a / aBase)
aBase *= base;
while (b / bBase)
bBase *= base;
return a*bBase + b < b*aBase + a; //当数较大时会产生int类型溢出
}
public:
string minNumber(vector<int>& nums) {
int len = nums.size();
if (len == 0) return "";
sort(nums.begin(), nums.end(), cmp);
string res = "";
for (int i = 0; i<len; ++i)
res += to_string(nums[i]);
return res;
}
};
为解决溢出的问题,可以在返回比较时进行强制转换: return ((long long int)a*bBase + b )< ((long long int)b*aBase + a);
解法2:将int类型vector的比较函数用字符串相连,比较大小。两遍类型转换,效率较差。
class Solution {
static bool cmp(const int& a, const int& b)//需是static类型
{
string A = to_string(a) + to_string(b);
string B = to_string(b) + to_string(a);
return A < B;
}
public:
string minNumber(vector<int>& nums) {
int len = nums.size();
if (len == 0) return "";
sort(nums.begin(), nums.end(), cmp);
string res = "";
for (int i = 0; i<len; ++i)
res += to_string(nums[i]);
return res;
}
};
解法3:将int数组先转为string数组,对string数组写比较函数,效率较好
class Solution {
static bool cmp(const string& a, const string& b)//需是static类型
{
return a + b < b + a; //当数较大时会产生int类型溢出
}
public:
string minNumber(vector<int>& nums) {
int len = nums.size();
if (len == 0) return "";
vector<string> numStr;
for (int i = 0; i<len; ++i)
numStr.push_back(to_string(nums[i]));
sort(numStr.begin(), numStr.end(), cmp);
string res = "";
for (int i = 0; i<len; ++i)
res += numStr[i];
return res;
}
};
用解法3求最大数时,可参考程序如下:
class Solution {
private:
static bool cmp(const string & str1, const string & str2) {
return str1+str2 > str2+str1;
}
public:
string largestNumber(vector<int>& nums) {
int len = nums.size();
if (len == 0)
return "";
vector<string> str(len); //已初始化长度,不用push_back, 直接根据下标赋值即可
for(int i = 0; i < len ; i++)
str[i] = to_string(nums[i]);
sort(str.begin(), str.end(), cmp);
string res = "";
/* //对含有多个0的处理,可用一个if (str[0] == "0")代替
int i = 0;
while (i < len-1 && str[i] == "0")
i++;
for(; i < len; i++)
res += str[i];
*/
if (str[0] == "0")
return "0";
for(int i = 0; i < len; i++)
res += str[i];
return res;
}
};