class Solution {
public:
string kthLargestNumber(vector<string>& nums, int k) {
priority_queue<int>q;
for(int i=0;i<nums.size();i++)
{
q.push(stoi(nums[i]));
}
while(!q.empty())
{
k--;
if(k==0)
{
return q.top();
}
q.pop();
}
return 0;
}
};
我试图解决 Leetcode 1985. 找出数组中第 K 个最大整数的问题。但我在第 14 行遇到编译错误( return q.top(); ),我不知道为什么会发生这种情况。
只要看一下代码,答案就很简单了。该函数应返回
std::string
,而您则返回 和 int
。您现在可能想通过使用 to_string
函数并将 int
转换为 std:string
来解决问题。
但是,这是行不通的。
该解决方案应该而且必须适用于字符串。
Constraints:
1 <= k <= nums.length <= 104
1 <= nums[i].length <= 100
nums[i] consists of only digits.
nums[i] will not have any leading zeros.
很明显,你不能在
int
中存储100位长的数字。因此,您还必须使用字符串排序。
但这会让事情变得困难,因为你需要采用所谓的自然排序。
示例:查看 2,3 和 200,然后,如果您比较字符串,3 将大于 200。这就是他们想要从您那里得到的。自然排序。
有很多可能的解决方案。这是其中之一:
#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>
#include <vector>
using namespace std::string_literals;
// FUNCTOR for Natural sort function. Limited to signed char strings
struct NaturalSort {
bool operator ()(const std::string& s1, const std::string& s2) {
// We want to iterate over both strings
const char* i1 = s1.data(); // Get a pointer to the beginning of string 1
const char* i2 = s2.data(); // Get a pointer to the beginning of string 2
// Result of comparison. 0 means equal, positive means s1>s2, negative means s1<s2
int result = 0;
// As long as both characters/numbers are equal and there are still characters in the string
do {
// If we found a digit at the same position in both strings
if (std::isdigit(*i1) and std::isdigit(*i2)) {
std::size_t pos1{}, pos2{}; // This will later indicate how many digits we read
// Convert the strings to numbers and compare them
result = std::stoi(i1, &pos1) - std::stoi(i2, &pos2);
// Set pointers to the position after the number
i1 += pos1; i2 += pos2;
}
else {
// Normal character
result = (*i1 - *i2);
++i1; ++i2;
}
} while ((result == 0) and (*i1 != 0 or *i2 != 0));
// Let's limit the output to -1, 0 ,1
return result < 0;
}
};
class Solution{
public:
std::string kthLargestNumber(std::vector<std::string>& nums, int k) {
std::sort(nums.begin(), nums.end(), NaturalSort());
return nums[nums.size()-k];
}
};
// Driver / test code
int main() {
std::vector<std::string> test{ "2"s,"3"s,"20"s,"30"s,"200"s,"300"s };
Solution solution{};
for (int k = 1; k <= test.size(); ++k)
std::cout << "With k=" << k << " the result would be: " << solution.kthLargestNumber(test, k) << '\n';
}