Java TreeMap Solution


  • 0
    Y
    public class Solution {
        public int[] maxSlidingWindow(int[] nums, int k) {
            if (nums.length == 0) {
                int[] ret = new int[0];
                return ret;
            }
            int[] ans = new int[nums.length - k + 1];
            TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
            for (int i = 0; i < k; i ++) {
                int n = nums[i];
                map.put(n, map.getOrDefault(n, 0) + 1);
            }
            for (int i = 0; i < nums.length - k + 1; i ++) {
                ans[i] = map.lastKey();
                int m = nums[i];
                int f = map.get(m);
                if (f == 1) map.remove(m);
                else map.put(m, f - 1);
                if (i + k < nums.length) map.put(nums[i + k], map.getOrDefault(nums[i + k], 0) + 1);
            }
            return ans;
        }
    }
    

Log in to reply
 

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