Java Solution using simple array beats 99% submissions


  • 0
    C
    public class Solution {
        public int[] maxSlidingWindow(int[] nums, int k) {
            if (nums == null || nums.length < k || k <= 0) return new int[0];
            
            int maxIdx = 0;
            int maxVal = nums[0];
            int[] res = new int[nums.length - k + 1];
            
            for (int i = 1; i < k; i++) {
                if (nums[i] > maxVal) {
                    maxVal = nums[i];
                    maxIdx = i;
                }
            }
            
            res[0] = maxVal;
            
            for (int i = 1; i < nums.length - k + 1; i++) {
                if (maxIdx < i) {
                    maxVal = nums[i];
                    maxIdx = i;
                    for (int j = i + 1; j < i + k; j++) {
                        if (nums[j] > maxVal) {
                            maxVal = nums[j];
                            maxIdx = j;
                        }
                    }
                }
                
                if (nums[i + k - 1] > maxVal) {
                    maxVal = nums[i + k - 1];
                    maxIdx = i + k - 1;
                }
                
                res[i] = maxVal;
            }
            
            return res;
        }
    }
    

Log in to reply
 

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