给定n个正整数数组,其中每个整数最多可以具有10 6的数字,请按升序打印数组元素。
Input: arr[] = {54, 724523015759812365462, 870112101220845, 8723}
Output: 54 8723 870112101220845 724523015759812365462
Explanation:
All elements of array are sorted in non-descending(i.e., ascending)
order of their integer value
Input: arr[] = {3643641264874311, 451234654453211101231,
4510122010112121012121}
Output: 3641264874311 451234654453211101231 4510122010112121012121
天真的方法是使用任意精度的数据类型,例如Python的int或Java的Biginteger类。但是这种方法不会有效果,因为将字符串内部转换为int然后执行排序将导致二进制数系统中加法和乘法运算的速度变慢。
高效的解决方案:由于整数的大小非常大,即使它不能适合C / C++的长数据类型,因此我们只需要将所有数字输入为字符串并使用比较函数对它们进行排序即可。以下是要点比较函数:-
- 如果两个字符串的长度不同,那么我们需要比较长度以决定排序顺序。
- 如果长度相同,那么我们只需要按字典顺序比较两个字符串。
假设:没有前导零。
C++
// Below is C++ code to sort the Big integers in
// ascending order
#include
using namespace std;
// comp function to perform sorting
bool comp(const string &left, const string &right)
{
// if length of both string are equals then sort
// them in lexicographically order
if (left.size() == right.size())
return left < right;
// Otherwise sort them according to the length
// of string in ascending order
else
return left.size() < right.size();
}
// Function to sort arr[] elements according
// to integer value
void SortingBigIntegers(string arr[], int n)
{
// Copy the arr[] elements to sortArr[]
vector sortArr(arr, arr + n);
// Inbuilt sort function using function as comp
sort(sortArr.begin(), sortArr.end(), comp);
// Print the final sorted array
for (auto &ele : sortArr)
cout << ele << " ";
}
// Driver code of above implementation
int main()
{
string arr[] = {"54", "724523015759812365462",
"870112101220845", "8723"};
int n = sizeof(arr) / sizeof(arr[0]);
SortingBigIntegers(arr, n);
return 0;
}
Python
# Below is Python code to sort the Big integers
# in ascending order
def SortingBigIntegers(arr, n):
# Direct sorting using lamda operator
# and length comparison
arr.sort(key = lambda x: (len(x), x))
# Driver code of above implementation
arr = ["54", "724523015759812365462",
"870112101220845", "8723"]
n = len(arr)
SortingBigIntegers(arr, n)
# Print the final sorted list using
# join method
print " ".join(arr)
Output: 54 8723 870112101220845 724523015759812365462
时间复杂度: O(sum * log(n))其中sum是所有字符串长度的总和,n是数组的大小
辅助空间: O(n)
类似帖子:
对大量数字进行排序