Simple solution. java and python


  • 0
    C

    Java beats 97%

    public class Solution {
        public int[] maxSlidingWindow(int[] nums, int k) {
            if (nums==null || nums.length==0) return new int[0];
            
            int[] ans = new int[nums.length - k + 1];
            int highest = max(nums, 0, k);
            ans[0] = highest;
            int last = nums[0];
            
            for (int i=1; i<nums.length-k+1; i++) {
                if (highest == last) highest = max(nums, i, k);
                else if (nums[i+k-1] > highest) highest = nums[i+k-1];
                
                ans[i] = highest;
                last = nums[i];
            }
            
            return ans;
            
        }
        
        public int max(int[] nums, int start, int k) {
            int max = nums[start];
            for (int i=start+1; i<start+k; i++) {
                if (nums[i] > max) max = nums[i];
            }
            return max;
        }
    }
    

    Python beats 99%

    class Solution(object):
        def maxSlidingWindow(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: List[int]
            """
            if not nums:
                return []
            
            highest = max(nums[:k])
            ans = [0]*(len(nums)-k+1)
            ans[0] = highest
            last = nums[0]
            
            for i in range(1, len(nums)-k+1):
                if highest == last:
                    highest = max(nums[i:i+k])
                elif nums[i+k-1] >= highest:
                    highest = nums[i+k-1]
                
                ans[i] = highest
                last = nums[i]
                
            return ans

Log in to reply
 

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