Get the median of k sorted arrays

来源:互联网 发布:职前教育网络学堂 编辑:程序博客网 时间:2024/06/05 01:54
public double mergekSortedArrays(int[][] arrays) {          // Write your code here          List<Containor> list = new LinkedList<>();        double res = 0;        if (arrays == null || arrays.length == 0 || arrays[0].length == 0) {              return 0;          }        int len = 0;        for (int[] array: arrays) {        len = len + array.length;        }        int medianIdx = len / 2;        boolean odd = true;        if (len % 2 == 0) {        odd = false;        }        PriorityQueue<Containor> queue = new PriorityQueue<>(11, new Comparator<Containor>(){              @Override              public int compare(Containor a, Containor b){                  return a.value - b.value;              }          });          for (int i = 0; i < arrays.length; i++) {              queue.offer(new Containor(i, 0, arrays[i][0]));          }          while (!queue.isEmpty()) {              Containor c = queue.poll();              list.add(c);            if (list.size() == medianIdx + 1 && odd) {            return c.value;            } else if (list.size() == medianIdx && !odd) {            Containor c2 = list.get(list.size() - 2);            return (c2.value + c.value)/2;            }            if (c.idxElement + 1 < arrays[c.idxArray].length) {                  queue.offer(new Containor(c.idxArray, c.idxElement + 1, arrays[c.idxArray][c.idxElement + 1]));              }          }          return res;      }            class Containor {          int idxArray;          int idxElement;          int value;          public Containor (int idxArray, int idxElement, int value) {              this.idxArray = idxArray;              this.idxElement = idxElement;              this.value = value;          }      }

0 0
原创粉丝点击