Find the Kth Largest Integer in the Array

本文介绍了一种使用快速选择算法找出字符串数组中第K大的整数的方法。该算法适用于处理包含重复数字的情况,并通过比较字符串长度及字典序实现了非递减排序。文章详细解释了算法流程并提供了实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

思路: quick select.  O(n*M); M is word length;

class Solution {
    public String kthLargestNumber(String[] nums, int k) {
        return String.valueOf(findKth(nums, 0, nums.length - 1, k));
    }
    
    private String findKth(String[] A, int start, int end, int k) {
        if(start == end) {
            return A[start];
        }
        int i = start; int j = end;
        int mid = start + (end - start) / 2;
        String pivot = A[mid];
        while(i <= j) {
            while(i <= j && compare(A[i], pivot) > 0) {
                i++;
            }
            while(i <= j && compare(A[j], pivot) < 0) {
                j--;
            }
            if(i <= j) {
                String temp = A[i];
                A[i] = A[j];
                A[j] = temp;
                i++;
                j--;
            }
        }
        
        if(start + k - 1 <= j) {
            return findKth(A, start, j, k);
        }
        if(start + k - 1 >= i) {
            return findKth(A, i, end, k - (i - start));
        }
        return A[j + 1];
    }
    
    private int compare(String a, String b) {
        if(a.length() == b.length()) {
            return a.compareTo(b);
        } else {
            return a.length() - b.length();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值