函数sort和nth_element之间的差异
作者:
autofry
,
2021-09-23 01:15:25
,
所有人可见
,
阅读 458
区别
nth_element函数能快速的找到第几大的数,但不能同时保证数组是有序的
而sort函数也能找到第几大的数,同时能保证数组是有序的,但找的时间不如nth_element函数要快
nth_element函数
class Solution {
public:
string kthLargestNumber(vector<string>& nums, int k) {
const int n = nums.size();
nth_element(nums.begin(),
nums.begin() + n - k,
nums.end(),
[](const string &s1, const string &s2) {
if (s1.size() != s2.size())
return s1.size() < s2.size();
for (int i = 0; i < s1.size(); i++)
if (s1[i] != s2[i])
return s1[i] < s2[i];
return false;
}
);
return nums[n - k];
}
};
sort函数
class Solution {
public:
string kthLargestNumber(vector<string>& nums, int k) {
const int n = nums.size();
sort(nums.begin(),
nums.end(),
[](const string &s1, const string &s2) {
if (s1.size() != s2.size())
return s1.size() < s2.size();
for (int i = 0; i < s1.size(); i++)
if (s1[i] != s2[i])
return s1[i] < s2[i];
return false;
}
);
return nums[n - k];
}
};