480. 滑动窗口中位数

480. 滑动窗口中位数

480. 滑动窗口中位数_第1张图片


Java:超出时间限制

class Solution {
    double[] ans;
    int j;

    private void sortAndSetAns(int k, Map<Integer, Integer> map) {
        List<Map.Entry<Integer,Integer>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list, (o1, o2) -> o1.getValue().compareTo(o2.getValue()));
        if (k % 2 == 1) {
            ans[j++] = list.get(k/2).getValue();
        } else {
            ans[j++] = list.get(k/2).getValue() / 2.0 + list.get(k/2 - 1).getValue() / 2.0;
        }
        list.clear();
    }

    public double[] medianSlidingWindow(int[] nums, int k) {
        ans = new double[nums.length - k + 1];
        j = 0;

        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < k; ++i) {
            map.put(i, nums[i]);
        }
        sortAndSetAns(k, map);

        for (int i = k; i < nums.length; ++i) {
            map.remove(i-k, map.get(i-k));
            map.put(i, nums[i]);
            sortAndSetAns(k, map);
        }

        return ans;
    }
}

你可能感兴趣的:(LeetCode刷题,算法)