publicdouble[] medianSlidingWindow2(int[] nums, int k) { if (nums == null || nums.length == 0){ returnnewdouble[0]; }
double[] res = newdouble[nums.length - k + 1]; int mid = k / 2; List<Integer> list = new ArrayList<>(); for (int i = 0; i < k; i++) { list.add(nums[i]); } Collections.sort(list);
for (int i = 0; i < nums.length - k + 1; i++) { //加入结果集 if (k % 2 == 0){ res[i] = list.get(mid - 1) / 2.0 + list.get(mid) / 2.0; }else{ res[i] = list.get(mid); }
publicdouble[] medianSlidingWindow3(int[] nums, int k) { if (nums == null || nums.length == 0){ returnnewdouble[0]; }
double[] res = newdouble[nums.length - k + 1]; int mid = k / 2; List<Integer> list = new ArrayList<>(); for (int i = 0; i < k; i++) { //优化:插入的时候就可以再利用二分查找顺便排好序 int idx = findIndex(list, nums[i]); list.add(idx, nums[i]); }
for (int i = 0; i < nums.length - k + 1; i++) { //加入结果集 if (k % 2 == 0){ res[i] = list.get(mid - 1) / 2.0 + list.get(mid) / 2.0; }else{ res[i] = list.get(mid); }
if (i + k == nums.length) break;
//去掉一个 //优化:去掉的时候也可以利用二分查找删除,就可以remove下标而不是remove元素 int idx = findIndex(list, nums[i]); list.remove(idx);