给定一个整数数组,请将其重新排序,以构造最小值。
注意事项:
The result may be very large, so you need to return a string instead of an integer.
样例
给定 [3, 32, 321],通过将数组重新排序,可构造 6 个可能性数字:
3+32+321=332321
3+321+32=332132
32+3+321=323321
32+321+3=323213
321+3+32=321332
321+32+3=321323
其中,最小值为 321323,所以,将数组重新排序后,该数组变为 [321, 32, 3]。
挑战 :
在原数组上完成,不使用额外空间。
#ifndef C379_H
#define C379_H
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
bool cmp(const int &a, const int &b)
{
string astr = to_string(a), bstr = to_string(b);
int alen = astr.size(), blen = bstr.size();
if (alen<blen)
{
for (int i = 0; i < alen; ++i)
{
if (astr[i] < bstr[i])
{
return true;
break;
}
else if (astr[i] == bstr[i])
{
if (i == astr.size() - 1)
{
string s1 = astr + bstr;
string s2 = bstr + astr;
for (int j = i + 1; j < s1.size(); ++j)
{
if (s1[j] < s2[j])
{
return true;
break;
}
else if (s1[j] == s2[j])
;
else
{
return false;
break;
}
}
}
}
else
{
return false;
break;
}
}
return true;
}
else
{
for (int i = 0; i < blen; ++i)
{
if (astr[i] < bstr[i])
{
return true;
break;
}
else if (astr[i] == bstr[i])
{
if (i == bstr.size() - 1)
{
string s1 = astr + bstr;
string s2 = bstr + astr;
for (int j = i + 1; j < s1.size(); ++j)
{
if (s1[j] < s2[j])
{
return true;
break;
}
else if (s1[j] == s2[j])
;
else
{
return false;
break;
}
}
}
}
else
{
return false;
break;
}
}
return false;
}
}
class Solution {
public:
/*
* @param nums: n non-negative integer array
* @return: A string
*/
string minNumber(vector<int> nums) {
// write your code here
if (nums.empty())
return NULL;
sort(nums.begin(), nums.end(), cmp);
string str;
for (int i = 0; i < nums.size(); ++i)
{
if (nums[i]!=0)
str += to_string(nums[i]);
if (i == nums.size() - 1 && str.empty())
str = "0";
}
return str;
}
};
#endif