Leetcode 5855 数组第K大的整数

news/2025/2/19 8:46:04/

在这里插入图片描述
在这里插入图片描述
这个题目就是一个排序问题,只不过排序的是字符串类型表示的整数。
看提示信息可知每个数字的长度最长可达100,因此不能够将字符串转化成数字。

做法很简单:自定义一个字符串数字比较函数,排序找到第k大的元素。
C++ 中字符串可以直接比较大小,很方便,不要使用 compare 函数会导致排序错误。

自带快排:
(比较函数记得定义成 static bool;符号与意义相同 <:从小到大;>:从大到小)

class Solution {
public:static bool cmp (string s1, string s2) {if(s1.size() == s2.size()) return s1 > s2;else return s1.size() > s2.size();}string kthLargestNumber(vector<string>& nums, int k) {sort(nums.begin(), nums.end(), cmp);return nums[k-1];}
};

堆排序代码:

class Solution {
public:struct cmp {bool operator () (string s1, string s2) {if(s1.size() == s2.size()) return s1 < s2;else return s1.size() < s2.size();}};string kthLargestNumber(vector<string>& nums, int k) {string out = "";priority_queue<string, vector<string>, cmp> que;for(int i=0; i<nums.size(); i++){que.push(nums[i]);}while(k > 0) {out = que.top();que.pop();k--;}return out;}
};

http://www.ppmy.cn/news/374939.html

相关文章

HDU - 5855 Less Time, More profit 最大权闭合子图 + 二分

传送门&#xff1a;HDU 5855 题意: 有n个工厂&#xff0c;m个商店 每个工厂有建造时间ti&#xff0c;花费payi 每个商店和k个工厂有关&#xff0c;如果这k个工厂都建造了&#xff0c;那么能获利proi 问你求收益&#xff08;∑pro−∑pay&#xff09;≥L时&#xff0c;首先满足…

[exgcd] Jzoj P5855 吃蛋糕

Description Beny 想要用蛋糕填饱肚子。Beny 一共想吃体积为 c 的蛋糕&#xff0c;他发现有两种蛋糕可以吃&#xff0c;一种体积为 a&#xff0c;一种体积为 b&#xff0c;但两种蛋糕各有特色。Beny 想知道他一共有多少种不同吃法&#xff0c; 使得他恰好可以填饱肚子。 Input …

leetcode 5855. 找出数组中的第 K 大整数(C++、java、python)

给你一个字符串数组 nums 和一个整数 k 。nums 中的每个字符串都表示一个不含前导零的整数。 返回 nums 中表示第 k 大整数的字符串。 注意&#xff1a;重复的数字在统计时会视为不同元素考虑。例如&#xff0c;如果 nums 是 ["1","2","2"]&am…

二分+贪心——HDU 5855

题目链接&#xff1a; http://acm.split.hdu.edu.cn/showproblem.php?pid5855参考博客&#xff1a; http://blog.csdn.net/queuelovestack/article/details/52222085分析&#xff1a;给出N个工厂&#xff0c;每个工厂给出建造时间和费用&#xff0c;给出M个商店&#xff0c;…

HDU5855 Less Time, More profit(最大权闭合子图)

题目 Source http://acm.hdu.edu.cn/showproblem.php?pid5855 Description The city planners plan to build N plants in the city which has M shops. Each shop needs products from some plants to make profit of proi units. Building ith plant needs investment of pa…

HDU 5855 Less Time, More profit 【最大流-最大权闭合子图】

作为多校签到题的存在…. 题意&#xff1a; n个工厂&#xff0c;m个商店 每个工厂有建造时间 ti &#xff0c;花费 payi 每个商店和k个工厂有关&#xff0c;如果这k个工厂都建造了&#xff0c;那么能获利 proi 问你求收益&#xff08;∑pro−∑pay&#xff09;≥L时&#…

HDU-5855 Less Time, More profit(最大权闭合图+二分)

题意&#xff1a; 有n个工厂和m个商店&#xff0c;商店已经存在&#xff0c;而工厂需要建造且需要一定的花费和一定的时间&#xff0c;工厂的建造可以同时建&#xff0c;如果建造了指定的工厂&#xff0c;相应的商店会获得一定的收入。给定一个L&#xff0c;求最少需要花费多长…

HDU 5855-最大权闭合图(-最小割应用)

题意就是一个裸的最大权闭合图: M个商店&#xff0c;N个工厂&#xff0c;每个商店获利的条件是建设了指定的k个工厂。求总获利不小于L&#xff0c;工厂建设的时间最大值最小是多少。 工厂到汇点建一条边pay[i]&#xff0c;源点到商店建一条边pro[i]&#xff0c;商店到需要的工…