Java one loop using PriorityQueue


  • 0
    public class Solution {
        public int[] maxSlidingWindow(int[] nums, int k) {
            if (nums == null || nums.length == 0 || k < 1) return new int[0];
            if (nums.length < k || k == 1) return nums;
            
            int[] res = new int[nums.length-k+1];
            
            Comparator<Integer> cmp;
            cmp = new Comparator<Integer>() {
                public int compare(Integer e1, Integer e2) {
                    return e2 - e1;
                }
            };
            
            Queue<Integer> q = new PriorityQueue<>(k, cmp);
            for (int i = 0; i < nums.length; ++i) {
                q.add(nums[i]);                // add a new number
                if (i >= k-1) {
                    res[i-(k-1)] = q.peek();   // take the max one
                    q.remove(nums[i-(k-1)]);   // remove the first number
                }
            }
            return res;
        }
    }
    

Log in to reply
 

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