GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — Leetcode-Java/leetcode/solution/src/SlidingWindowMedian.java at master · Tulpen/Leetcode-Java Expand file tree/ Copy pathSlidingWindowMedian.javaMore file actions 84 lines (73 loc) · 2.2 KB / Copy pathSlidingWindowMedian.javaFile metadata and controls84 lines (73 loc) · 2.2 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 import java.util.Comparator; import java.util.Map; import java.util.TreeMap; /** * https://leetcode.com/articles/sliding-window-median/ * 和 #295 Find Median from Data Stream 比较类似 */ public class SlidingWindowMedian { /** * 这题如果用PriorityQueue则复杂度为O(nk),因为其删除复杂度为O(n) * 改为TreeMap会降为O(nlgk) */ public double[] medianSlidingWindow(int[] nums, int k) { MyMap up = new MyMap(); MyMap down = new MyMap(Comparator.reverseOrder()); double[] result = new double[nums.length - k + 1]; for (int i = 0; i < nums.length; i++) { up.myAdd(nums[i]); down.myAdd(up.myPollFirst()); if (i >= k) { if (up.containsKey(nums[i - k])) { up.myRemove(nums[i - k]); } else { down.myRemove(nums[i - k]); } } if (up.size < down.size) { up.myAdd(down.myPollFirst()); } if (i >= k - 1) { result[i - k + 1] = up.size == down.size ? ((double) up.firstKey() + down.firstKey()) / 2 : up.firstKey(); } } return result; } class MyMap extends TreeMap<Integer, Integer> { int size; MyMap() { super(); } MyMap(Comparator<Integer> comparator) { super(comparator); } void myAdd(int n) { put(n, getOrDefault(n, 0) + 1); size++; } boolean myRemove(int n) { int count = getOrDefault(n, 0); if (count == 0) { return false; } if (count == 1) { remove(n); } else { put(n, count - 1); } size--; return true; } int myPollFirst() { Map.Entry<Integer, Integer> entry = firstEntry(); if (entry.getValue() == 1) { pollFirstEntry(); } else { put(entry.getKey(), entry.getValue() - 1); } size--; return entry.getKey(); } } } |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |