very clean 3-line C# solution O(n): using List<T>, and generalized for any k-th largest element, 165ms


  • 0
    C

    Do not over-complicate things. Express your intent through code.

    public class Solution 
    {
        const int k = 3;    
        
        public int ThirdMax(int[] nums) 
        {
            var max = new List<int>();  int idx;
            
            foreach (var num in nums)
            {
                if ((idx = max.BinarySearch(num)) < 0)
                {
                    max.Insert(~idx, num);   if (max.Count > k)  max.RemoveAt(0);
                }
            }
            
            return (max.Count == k) ? max.First() : max.Last();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.