返回介绍

solution / 1900-1999 / 1985.Find the Kth Largest Integer in the Array / README_EN

发布于 2024-06-17 01:03:12 字数 3901 浏览 0 评论 0 收藏 0

1985. Find the Kth Largest Integer in the Array

中文文档

Description

You are given an array of strings nums and an integer k. Each string in nums represents an integer without leading zeros.

Return _the string that represents the _kth_ largest integer in _nums.

Note: Duplicate numbers should be counted distinctly. For example, if nums is ["1","2","2"], "2" is the first largest integer, "2" is the second-largest integer, and "1" is the third-largest integer.

 

Example 1:

Input: nums = ["3","6","7","10"], k = 4
Output: "3"
Explanation:
The numbers in nums sorted in non-decreasing order are ["3","6","7","10"].
The 4th largest integer in nums is "3".

Example 2:

Input: nums = ["2","21","12","1"], k = 3
Output: "2"
Explanation:
The numbers in nums sorted in non-decreasing order are ["1","2","12","21"].
The 3rd largest integer in nums is "2".

Example 3:

Input: nums = ["0","0"], k = 2
Output: "0"
Explanation:
The numbers in nums sorted in non-decreasing order are ["0","0"].
The 2nd largest integer in nums is "0".

 

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.

Solutions

Solution 1

class Solution:
  def kthLargestNumber(self, nums: List[str], k: int) -> str:
    def cmp(a, b):
      if len(a) != len(b):
        return len(b) - len(a)
      return 1 if b > a else -1

    nums.sort(key=cmp_to_key(cmp))
    return nums[k - 1]
class Solution {
  public String kthLargestNumber(String[] nums, int k) {
    Arrays.sort(
      nums, (a, b) -> a.length() == b.length() ? b.compareTo(a) : b.length() - a.length());
    return nums[k - 1];
  }
}
class Solution {
public:
  string kthLargestNumber(vector<string>& nums, int k) {
    auto cmp = [](const string& a, const string& b) { return a.size() == b.size() ? a > b : a.size() > b.size(); };
    sort(nums.begin(), nums.end(), cmp);
    return nums[k - 1];
  }
};
func kthLargestNumber(nums []string, k int) string {
  sort.Slice(nums, func(i, j int) bool {
    a, b := nums[i], nums[j]
    if len(a) == len(b) {
      return a > b
    }
    return len(a) > len(b)
  })
  return nums[k-1]
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文