简体   繁体   中英

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.

Note that it is the kth largest element in the sorted order, not the kth distinct element.

Example 1:

Input: nums = [3,2,1,5,6,4], k = 2 Output: 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

  1. You do sort in ascending order std::sort(iterator begin, iterator end) . That.s good. After that, you have sorted vector : 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.

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). That's not good. Leave duplicates as you said in post.

  2. You return int. But what's stored in this int? num.size() - k . What number is num.size() ? 6 , because vector has six elements. K = 2 (from input). So, result is 4. You return int with value 4 . You don't return any element from vector or sth like. You return size of vector minus const (parameter). But value 4 is good, but you have to do with it something more.

Think about your return. Hope it's help.

PS. Don't use namespace std. Always go with std::sort etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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