LeetCode: Kth Largest Element in an Array (sorting)

https://leetcode.com/problems/kth-largest-element-in-an-array/, problem statement:

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given [3,2,1,5,6,4] and k = 2, return 5.
Note: 
You may assume k is always valid, 1 ≤ k ≤ array's length.
Two-lines solution: sort & index. Code's below, cheers, Marcelo.


    public class Solution
    {
        public int FindKthLargest(int[] nums, int k)
        {
            Array.Sort(nums);
            return nums[nums.Length - k];
        }
    }

Comments

  1. Haha, I can only imagine what were solutions which took >600ms doing :) Technically sorting an entire array is not necessary and a simple algorithm based on a quick sort partitioning is usually faster - it takes only 9ms in C++ and beats ~92% of other solutions. FYI, C++ also has a way to cheat - nth_element:

    int findKthLargest(const vector& nums, int k) {
    nth_element(nums.begin(), nums.end() - k, nums.end());
    return nums[nums.size()-k];
    }

    Thanks for sharing!

    ReplyDelete
    Replies
    1. Ha, didn't know about the nth_element function, it was like it was meant to solve this problem! :)

      Delete
    2. there are lots of hidden gems in C++'s standard library :)

      Delete
  2. Thanks for sharing this blog its very informative and useful for us.

    ซอมบี้

    ReplyDelete

Post a Comment

Popular posts from this blog

Golang vs. C#: performance characteristics (simple case study)

Claude vs ChatGPT: A Coder's Perspective on LLM Performance

ProjectEuler Problem 719 (some hints, but no spoilers)