Find kth largest elements In unsorted array

By   Tewodros   Date Posted: Oct. 11, 2023  Hits: 333   Category:  Algorithm   Total Comment: 0             A+ A-


side

  public static IList<int> Find(int [] nums, int k)

    {

        IList<int> ans = new List<int>();

        var set = new SortedSet<int>();
 

        for(int i=0; i<nums.Length; i++)

        {

            if(set.Count < k)

                set.Add(nums[i]);

            else if(nums[i] > set.Min)

            {

                set.Remove(set.Min);

                set.Add(nums[i]);

            }

        }
 

        foreach(int num in set)

        {

            ans.Add(num);

        }


 

        return ans;

    }


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* vrbzji

Back to Top