简体   繁体   English

215. 数组中的第 K 个最大元素 C++ 解决方案不起作用

[英]215. Kth Largest Element in an Array C++ Solution Not Working

Given an integer array nums and an integer k, return the kth largest element in the array.给定一个整数数组 nums 和一个整数 k,返回数组中第 k 个最大的元素。

Note that it is the kth largest element in the sorted order, not the kth distinct element.请注意,它是排序顺序中的第 k 个最大元素,而不是第 k 个不同元素。

Example 1:示例 1:

Input: nums = [3,2,1,5,6,4], k = 2 Output: 5输入:nums = [3,2,1,5,6,4], k = 2 输出:5

My Solution Is Below and I do not understand why it is not working.我的解决方案如下,我不明白为什么它不起作用。 Maybe I am reading the question wrong?也许我读错了问题? Can someone please explain.有人可以解释一下。

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        sort(nums.begin(), nums.end() );
        nums.erase(unique(nums.begin(), nums.end() ), nums.end() );
        
        return nums.size() - k;
        
    }
};

Let's go through your function, with your example让我们用你的例子来看看你的功能

Input: nums = [3,2,1,5,6,4], k = 2 Output: 5输入:nums = [3,2,1,5,6,4], k = 2 输出:5

  1. You do sort in ascending order std::sort(iterator begin, iterator end) .你按升序排序std::sort(iterator begin, iterator end) That.s good.那挺好的。 After that, you have sorted vector : 1, 2, 3, 4, 5, 6之后,您对向量进行了排序1, 2, 3, 4, 5, 6

Edit:// I haven't noticed it: (so second point is correct now).编辑://我没有注意到它:(所以第二点现在是正确的)。

Note that it is the kth largest element in the sorted order, not the kth distinct element.请注意,它是排序顺序中的第 k 个最大元素,而不是第 k 个不同元素。

So you should erease duplicates.所以你应该删除重复项。

  1. You erease duplicate value.您消除了重复值。 After that, you have sorted vector without duplicates : 1, 2, 3, 4, 5, 6 (same as before, cos all values are distinct).之后,您对向量进行了排序,没有重复1、2、3、4、5、6 (与以前相同,因为所有值都不同)。 That's not good.这不好。 Leave duplicates as you said in post.留下你在帖子中说的重复项。

  2. You return int.你返回整数。 But what's stored in this int?但是这个 int 中存储了什么? num.size() - k . num.size() - k What number is num.size() ? num.size()多少? 6 , because vector has six elements. 6 ,因为向量有六个元素。 K = 2 (from input). K = 2(来自输入)。 So, result is 4. You return int with value 4 .因此,结果为 4。您返回值为4 的int You don't return any element from vector or sth like.您不会从向量或诸如此类的东西返回任何元素。 You return size of vector minus const (parameter).您返回向量减去 const (参数)的大小。 But value 4 is good, but you have to do with it something more.但是值4很好,但你必须用它做更多的事情。

Think about your return.想想你的回报。 Hope it's help.希望它有帮助。

PS.附注。 Don't use namespace std.不要使用命名空间 std。 Always go with std::sort etc.始终使用std::sort等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM