C# solution by LinkedList


  • 1
    S
    public class Solution {
        public int[] MaxSlidingWindow(int[] nums, int k) 
        {
            if(nums == null || nums.Count() == 0 || k<=0)
                return nums;
            var result = new List<int>();
            var ll = new LinkedList<int>();
            for(int i = 0; i<nums.Count(); i++)
            {
                if(ll.Any() && ll.First.Value <= i-k)
                {
                    ll.RemoveFirst();
                }
                while(ll.Any() && nums[ll.Last.Value]<=nums[i])
                {
                    ll.RemoveLast();
                }
                ll.AddLast(i);
                if(i-k+1 >=0)
                    result.Add(nums[ll.First.Value]);    
            }
            return result.ToArray();
        }
    }
    

  • 0

    Great solution. a small suggestion: Use Length insteading of Count(), it might make it faster. Since Length is a property and Count() is a LINQ extension of IEnumerable<T>.


Log in to reply
 

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