|
| 1 | +// Title: Find the Kth Largest Integer in the Array |
| 2 | +// Description: |
| 3 | +// You are given an array of strings nums and an integer k. |
| 4 | +// Each string in nums represents an integer without leading zeros. |
| 5 | +// Return the string that represents the kth largest integer in nums. |
| 6 | +// Note: |
| 7 | +// Duplicate numbers should be counted distinctly. |
| 8 | +// For example, if nums is ["1","2","2"], "2" is the first largest integer, |
| 9 | +// "2" is the second-largest integer, and "1" is the third-largest integer. |
| 10 | +// Link: https://leetcode.com/problems/find-the-kth-largest-integer-in-the-array/ |
| 11 | + |
| 12 | +// Time complexity: O(n) |
| 13 | +// Space complexity: O(1) |
| 14 | +class Solution { |
| 15 | +public: |
| 16 | + std::string kthLargestNumber(std::vector<std::string> &nums, int k) { |
| 17 | + auto target = nums.end() - k; |
| 18 | + |
| 19 | + /* |
| 20 | + void std::nth_element(first, nth, last, comp): |
| 21 | + Rearranges the elements in the range [first,last), |
| 22 | + in such a way that the element at the nth position is the element |
| 23 | + that would be in that position in a sorted sequence. |
| 24 | + */ |
| 25 | + std::nth_element( |
| 26 | + nums.begin(), target, nums.end(), |
| 27 | + [](std::string a, std::string b) { |
| 28 | + // If the two numbers have different lengths, |
| 29 | + // then the number with more digits is larger. |
| 30 | + if (a.length() != b.length()) return a.length() < b.length(); |
| 31 | + |
| 32 | + // Otherwise, the two numbers have the same length, |
| 33 | + // just compare them with lexicographical order. |
| 34 | + // Note: The time complexity of this comparison is actually O(len(a)+len(b)) |
| 35 | + return a < b; |
| 36 | + } |
| 37 | + ); |
| 38 | + |
| 39 | + return *target; |
| 40 | + } |
| 41 | +}; |
0 commit comments