public ListNode mergeKLists(ArrayList<ListNode> lists) {

    if (lists.size() == 0) return null;

    PriorityQueue<ListNode> q =
        new PriorityQueue<ListNode>(
            lists.size(),
            new Comparator<ListNode>() {

              public int compare(ListNode a, ListNode b) {
                if (a.val > b.val) return 1;
                else if (a.val == b.val) return 0;
                else return -1;
              }
            });

    for (ListNode i : lists) if (i != null) q.add(i);

    ListNode head = new ListNode(-1);
    ListNode pre = head;

    while (q.size() != 0) {

      ListNode temp = q.poll();
      pre.next = temp;

      if (temp.next != null) q.add(temp.next);

      pre = pre.next;
    }

    return head.next;
  }
Ejemplo n.º 2
1
  public static void main(String[] args) throws IOException {
    in = new Reader();
    out = new PrintWriter(System.out, true);

    int N = in.nextInt();

    PriorityQueue<Long> pq = new PriorityQueue<Long>();
    for (int i = 0; i < N; i++) pq.add(in.nextLong());

    long cost = 0;
    while (pq.size() > 1) {
      long a = pq.poll() + pq.poll();
      cost += a;
      pq.add(a);
    }

    out.println(cost);
  }
Ejemplo n.º 3
0
 public void add(int x) {
   if (min.size() <= max.size()) {
     min.add(x);
   } else {
     max.add(x);
   }
 }
Ejemplo n.º 4
0
  public static void main(String args[]) throws IOException {

    String text = "C:\\Users\\Roshan Rajan\\Desktop\\squaredance.txt";
    String gender = "";
    PriorityQueue<String> men = new PriorityQueue<String>();
    PriorityQueue<String> women = new PriorityQueue<String>();
    BufferedReader input = new BufferedReader(new FileReader(text));
    String line = null;
    while ((line = input.readLine()) != null) {
      gender = line.substring(0, 1);
      if (gender.equals("M")) men.add(line.substring(2));
      else women.add(line.substring(2));
    }
    input.close();

    while (!men.isEmpty() && !women.isEmpty()) {
      System.out.println("The couples are ");
      System.out.println(men.poll() + " is Dancing with " + women.poll());
    }
    if (men.isEmpty()) {
      System.out.println(women.size() + " girls are Waiting to Dance");
      System.out.println(women.peek() + " is the first one waiting");
    }
    if (women.isEmpty()) {
      System.out.println(men.size() + " guys are Waiting to Dance");
      System.out.println(men.peek() + " is the first one waiting");
    }
  }
 // Busqueda usando A*
 public static int search() {
     HashSet<State> v = new HashSet<>();
     Giros mano = new Giros();
     ArrayList<int[][]>aux;
     
     finall = inicial.createGoalState();
     Q.add(inicial);
     Node actual;
     int cont = 0;
     
     while ( !(actual = Q.remove()).estado.equals(finall.estado) ) {
         
         if(v.contains(actual.estado)) 
             continue;
         System.out.println(actual.estado+" "+actual.costo_hasta_aqui+" "+actual.costo_total);
         System.out.println("->\n"+((NodeCubo)actual).getValue() );
         
         v.add(actual.estado);
         int ca = actual.costo_hasta_aqui + 1;
         
         //Realiza Movimientos
         for( int i=0; i<12; i++ ){
             aux = mano.girar( ((Cubo)actual.getValue()).getCubo(), i);
             Node nuevo = new NodeCubo(ca, ca+Heuristica.h1((Cubo)actual.getValue()), new Cubo( aux, ((Cubo)inicial.getValue()).getColors() ) );
             Q.add( (Node)nuevo );
         }
         cont++;
     }
     return cont;
 }
  public ListNode mergeKLists(ListNode[] lists) {
    if (lists == null || lists.length == 0) return null;

    PriorityQueue<ListNode> queue =
        new PriorityQueue<ListNode>(
            lists.length,
            new Comparator<ListNode>() {
              @Override
              public int compare(ListNode a, ListNode b) {
                if (a.val > b.val) return 1;
                else if (a.val == b.val) return 0;
                else return -1;
              }
            });

    for (ListNode list : lists) {
      if (list != null) queue.add(list);
    }

    ListNode head = new ListNode(0);
    ListNode p = head;
    while (queue.size() > 0) {
      ListNode tmp = queue.poll();
      p.next = tmp;

      // keep adding next node in list
      if (tmp.next != null) queue.add(tmp.next);

      p = p.next;
    }

    return head.next;
  }
Ejemplo n.º 7
0
 public static void main(String[] args) {
   Scanner in = new Scanner(System.in);
   PriorityQueue<Node> pq = new PriorityQueue<Node>();
   HashSet<Integer> visited = new HashSet<Integer>();
   int n = in.nextInt();
   int[][] am = new int[n][n];
   for (int i = 0; i < n; i++)
     for (int j = 0; j < n; j++) {
       am[i][j] = in.nextInt();
       if (i == j) am[i][j] = Integer.MAX_VALUE;
     }
   n = in.nextInt();
   int a, b;
   while (n-- > 0) {
     a = in.nextInt() - 1;
     b = in.nextInt() - 1;
     am[a][b] = 0;
     am[b][a] = 0;
   }
   int ret = 0;
   pq.add(new Node(0, 0));
   Node curr;
   while (!pq.isEmpty()) {
     curr = pq.poll();
     if (visited.contains(curr.a)) continue;
     ret += curr.w;
     visited.add(curr.a);
     for (int i = 0; i < am.length; i++) {
       pq.add(new Node(i, am[curr.a][i]));
     }
   }
   System.out.println(ret);
 }
Ejemplo n.º 8
0
  /**
   * Get top N elements
   *
   * @param vec the vec to extract the top elements from
   * @param N the number of elements to extract
   * @return the indices and the sorted top N elements
   */
  private static List<Double> getTopN(INDArray vec, int N) {
    ArrayComparator comparator = new ArrayComparator();
    PriorityQueue<Double[]> queue = new PriorityQueue<>(vec.rows(), comparator);

    for (int j = 0; j < vec.length(); j++) {
      final Double[] pair = new Double[] {vec.getDouble(j), (double) j};
      if (queue.size() < N) {
        queue.add(pair);
      } else {
        Double[] head = queue.peek();
        if (comparator.compare(pair, head) > 0) {
          queue.poll();
          queue.add(pair);
        }
      }
    }

    List<Double> lowToHighSimLst = new ArrayList<>();

    while (!queue.isEmpty()) {
      double ind = queue.poll()[1];
      lowToHighSimLst.add(ind);
    }
    return Lists.reverse(lowToHighSimLst);
  }
Ejemplo n.º 9
0
  /**
   * @param k: The number k.
   * @return: The kth prime number as description.
   */
  public long kthPrimeNumber(int k) {
    PriorityQueue<Long> queue = new PriorityQueue<Long>();
    HashMap<Long, Boolean> map = new HashMap<Long, Boolean>();

    Long[] Primes = new Long[3];
    Primes[0] = Long.valueOf(3);
    Primes[1] = Long.valueOf(5);
    Primes[2] = Long.valueOf(7);

    for (int i = 0; i < Primes.length; ++i) {
      queue.add(Primes[i]);
      map.put(Primes[i], true);
    }

    Long number = Primes[0];
    for (int i = 1; i <= k; ++i) {
      number = queue.poll();
      for (int j = 0; j < Primes.length; ++j) {
        if (map.containsKey(number * Primes[j])) {
          continue;
        } else {
          map.put(number * Primes[j], true);
          queue.add(number * Primes[j]);
        }
      }
    }
    return number;
  }
Ejemplo n.º 10
0
  public List<int[]> getSkyline(int[][] buildings) {
    if (buildings == null || buildings.length == 0) {
      return Collections.emptyList();
    }

    final PriorityQueue<Building> endings =
        new PriorityQueue<>((v1, v2) -> Integer.compare(v1.to, v2.to));
    final PriorityQueue<Integer> heights = new PriorityQueue<>((v1, v2) -> Integer.compare(v2, v1));

    final List<int[]> result = new ArrayList<>();

    // iterate over each of the building
    for (int[] build : buildings) {
      final Building building = new Building(build);

      while (endings.size() > 0 && endings.peek().to < building.from) {
        removeBuildings(endings, heights, result);
      }

      if (heights.size() == 0 || building.height > heights.peek()) {
        result.add(new int[] {building.from, building.height});
      }
      heights.add(building.height);
      endings.add(building);
    }

    while (endings.size() > 0) {
      removeBuildings(endings, heights, result);
    }

    return result;
  }
Ejemplo n.º 11
0
  public int[] maxSlidingWindow(int[] nums, int k) {
    if (nums == null || nums.length == 0) {
      return new int[0];
    }
    int len = nums.length;
    int max = Integer.MIN_VALUE;
    PriorityQueue<Integer> heap = new PriorityQueue<Integer>(k, new heapComparator());
    for (int i = 0; i < Math.min(k, len); i++) {
      heap.add(nums[i]);
    }

    if (k >= len) {
      int[] edge = new int[1];
      edge[0] = heap.peek();
      return edge;
    }
    int[] res = new int[len - k + 1];
    int index = 0;
    for (int i = k; i < len; i++) {
      res[index] = heap.peek();
      index++;
      heap.remove(nums[i - k]);
      heap.add(nums[i]);
    }
    res[index] = heap.peek();
    return res;
  }
Ejemplo n.º 12
0
  public static ListNode mergeKlists(List<ListNode> lists) {
    if (lists.size() == 0) return null;

    PriorityQueue<ListNode> p =
        new PriorityQueue<ListNode>(
            lists.size(),
            new Comparator<ListNode>() {
              @Override
              public int compare(ListNode a, ListNode b) {
                return a.val - b.val;
              }
            });

    for (ListNode list : lists) {
      if (list != null) p.add(list);
    }

    ListNode head = new ListNode(0);
    ListNode result = head;

    while (p.size() > 0) {
      ListNode temp = p.poll();
      result.next = temp;

      if (temp.next != null) {
        p.add(temp.next);
      }

      result = result.next;
    }
    return head.next;
  }
 public void testClear() {
   PriorityQueue<Integer> pq = new IntegerQueue(3);
   pq.add(2);
   pq.add(3);
   pq.add(1);
   assertEquals(3, pq.size());
   pq.clear();
   assertEquals(0, pq.size());
 }
  @SuppressWarnings("unchecked")
  public int getMinimumMoves(String[] board) {
    PriorityQueue<Long> pq = new PriorityQueue<Long>();
    HashMap<Long, Integer> map = new HashMap<Long, Integer>();

    ArrayList<Integer> pieces = new ArrayList<Integer>();
    for (int i = 0; i < 5; i++) {
      for (int j = 0; j < 5; j++) {
        if (board[i].charAt(j) == '*') {
          pieces.add((i << 3) | j);
        }
      }
    }
    N = pieces.size();

    pq.add(pack(pieces));
    while (pq.size() > 0) {
      long a = pq.poll();
      long k = a & 0xFFFFFFFFL;
      int c = (int) (a >>> 32);

      if (map.containsKey(k)) continue;
      map.put(k, c);

      ArrayList<Integer> unpack = unpack(k);

      if (connected(unpack)) return c;

      for (int i = 0; i < N; i++) {
        int piece = unpack.get(i);
        int x = piece >>> 3;
        int y = piece & 0x7;

        for (int j = 0; j < dir.length; j++) {
          ArrayList<Integer> copy = (ArrayList<Integer>) unpack.clone();
          copy.remove(i);

          if (x + dir[j][0] < 0 || x + dir[j][0] >= 5 || y + dir[j][1] < 0 || y + dir[j][1] >= 5)
            continue;
          int newp = ((x + dir[j][0]) << 3) | (y + dir[j][1]);

          if (copy.contains(newp)) continue;
          copy.add(newp);

          long test = pack(copy);

          if (map.get(test) == null || map.get(test) > c + 1) {
            pq.add((((long) c + 1) << 32) | test);
          }
        }
      }
    }
    return -1;
  }
Ejemplo n.º 15
0
  public static void main(String[] args) {
    PriorityQueue<GregorianCalendar> pq =
        new PriorityQueue<GregorianCalendar>(); // 优先级队列对GC设置优先级:月->日
    pq.add(new GregorianCalendar(1906, Calendar.DECEMBER, 9)); // G. Hopper
    pq.add(new GregorianCalendar(1815, Calendar.DECEMBER, 10)); // A. Lovelace
    pq.add(new GregorianCalendar(1923, Calendar.DECEMBER, 3)); // J. von Neumann
    pq.add(new GregorianCalendar(1910, Calendar.JUNE, 22)); // K. Zuse

    System.out.println("Iterating over elements...");
    for (GregorianCalendar date : pq) System.out.println(date.get(Calendar.YEAR));
    System.out.println("Removing elements...");
    while (!pq.isEmpty()) System.out.println(pq.remove().get(Calendar.YEAR));
  }
  // Time: O(nlogk)
  // Space: O(1)
  public int findKthLargest(int[] nums, int k) {
    PriorityQueue<Integer> heap = new PriorityQueue<Integer>();

    for (int num : nums) {
      if (heap.size() < k) {
        heap.add(num);
      } else {
        if (heap.peek() < num) {
          heap.poll();
          heap.add(num);
        }
      }
    }
    return heap.peek();
  }
Ejemplo n.º 17
0
  public void addCommand(Command command, String... names) {

    for (String name : names) {
      commandMap.put(name, command);
      commandsAlphabetized.add(name);
    }
  }
 public void adjustTellerNumber() {
   // This is actually a control system. By adjusting
   // the numbers, you can reveal stability issues in
   // the control mechanism.
   // If line is too long, add another teller:
   if (customers.size() / workingTellers.size() > 2) {
     // If tellers are on break or doing
     // another job, bring one back:
     if (tellersDoingOtherThings.size() > 0) {
       Teller teller = tellersDoingOtherThings.remove();
       teller.serveCustomerLine();
       workingTellers.offer(teller);
       return;
     }
     // Else create (hire) a new teller
     Teller teller = new Teller(customers);
     exec.execute(teller);
     workingTellers.add(teller);
     return;
   }
   // If line is short enough, remove a teller:
   if (workingTellers.size() > 1 && customers.size() / workingTellers.size() < 2)
     reassignOneTeller();
   // If there is no line, we only need one teller:
   if (customers.size() == 0) while (workingTellers.size() > 1) reassignOneTeller();
 }
Ejemplo n.º 19
0
  static void test00() {
    Aron.beg();
    PriorityQueue<Interval> queue = new PriorityQueue<Interval>();
    Stack<Interval> stack = new Stack<Interval>();
    int[] arr1 = {4, 1, 2, 6, 9};
    int[] arr2 = {5, 1, 4, 9, 10};

    for (int i = 0; i < arr1.length; i++) {
      queue.add(new Interval(arr1[i], arr2[i]));
    }
    if (queue.size() > 0) {
      stack.push(queue.remove());
    }
    while (!queue.isEmpty()) {
      Interval top = stack.peek();
      Interval inter = queue.remove();
      if (top.end < inter.begin) stack.push(inter);
      else {
        stack.peek().end = Math.max(stack.peek().end, inter.end);
      }
    }
    while (!stack.empty()) {
      System.out.println("[" + stack.peek().begin + " " + stack.peek().end + "]");
      stack.pop();
    }

    Aron.end();
  }
Ejemplo n.º 20
0
  private static PencilPosition findShortestRoute(int[][] maze) {
    // all found solutions to the maze
    PriorityQueue<PencilPosition> solutions =
        new PriorityQueue<PencilPosition>(5, new PencilPositionComparator());
    // bread-first search queue
    Queue<PencilPosition> routes = new LinkedList<PencilPosition>();
    // set of already visited positions
    Set<PencilPosition> visitedPositions = new HashSet<PencilPosition>();

    // add the starting positions, which is always (0,0)
    routes.add(new PencilPosition(0, 0, false, null));

    while (!routes.isEmpty()) {
      PencilPosition position = routes.poll();

      // if this is the destinations position then we've found a solution
      if (0 == maze[position.row][position.column]) {
        solutions.add(position);
        continue;
      }

      // if we haven't already visited this position
      if (!visitedPositions.contains(position)) {
        routes.addAll(findPossibleRoutes(position, maze));
        visitedPositions.add(position);
      }
    }

    return solutions.poll();
  }
Ejemplo n.º 21
0
  public int nthUglyNumber(int n) {
    if (n <= 0) return 0;

    PriorityQueue<Long> queue = new PriorityQueue<>();
    queue.add(1l);

    long result = 0;
    for (int i = 1; i <= n; i++) {
      result = queue.poll();
      while (!queue.isEmpty() && queue.peek() == result) queue.poll();
      queue.add(result * 2);
      queue.add(result * 3);
      queue.add(result * 5);
    }
    return (int) result;
  }
  public static void testPQ(int count, Random gen) {
    PriorityQueue<Integer> pq = new IntegerQueue(count);
    int sum = 0, sum2 = 0;

    for (int i = 0; i < count; i++) {
      int next = gen.nextInt();
      sum += next;
      pq.add(next);
    }

    //      Date end = new Date();

    //      System.out.print(((float)(end.getTime()-start.getTime()) / count) * 1000);
    //      System.out.println(" microseconds/put");

    //      start = new Date();

    int last = Integer.MIN_VALUE;
    for (int i = 0; i < count; i++) {
      Integer next = pq.pop();
      assertTrue(next.intValue() >= last);
      last = next.intValue();
      sum2 += last;
    }

    assertEquals(sum, sum2);
    //      end = new Date();

    //      System.out.print(((float)(end.getTime()-start.getTime()) / count) * 1000);
    //      System.out.println(" microseconds/pop");
  }
Ejemplo n.º 23
0
 /**
  * käy solmun vanhemmat ja pistää ne priorityqueue:n
  *
  * @param käydytsolmut
  * @param vikasolmu
  * @return
  */
 public PriorityQueue<Solmu> käysolmuttakaperin(
     PriorityQueue<Solmu> käydytsolmut, Solmu vikasolmu) {
   if (!vikasolmu.onkoalkusolmu) {
     käydytsolmut.add(vikasolmu);
     käysolmuttakaperin(käydytsolmut, vikasolmu.vanhempi);
   }
   return käydytsolmut;
 }
Ejemplo n.º 24
0
  @Override
  void solve(Set<? extends Job> jobs) {
    Job[] sortedJobs = jobs.toArray(new Job[jobs.size()]);
    Arrays.sort(sortedJobs, Job::compareArrivalTime);

    processTime = totWT = 0;
    long usefulTime = 0;
    int jobCount = jobs.size();
    PriorityQueue<Job> queue = new PriorityQueue<>(Job::compareBurstTime);
    for (Job job : sortedJobs) {
      if (job == null) {
        jobCount--;
        continue;
      }

      while (!queue.isEmpty() && processTime < job.getArrivalTime()) {
        Job nextJob = queue.poll();
        long arrivalTime = nextJob.getArrivalTime();
        long burstTime = nextJob.getBurstTime();

        if (processTime < nextJob.getArrivalTime()) {
          processList.add(new RunningProcess("Idle", arrivalTime - processTime));
          processTime = arrivalTime;
        }

        processList.add(new RunningProcess("P" + nextJob.getId(), burstTime));
        usefulTime += burstTime;
        totWT += processTime - arrivalTime;
        processTime += burstTime;
      }

      queue.add(job);
    }

    while (!queue.isEmpty()) {
      Job nextJob = queue.poll();
      long arrivalTime = nextJob.getArrivalTime();
      long burstTime = nextJob.getBurstTime();

      if (processTime < nextJob.getArrivalTime()) {
        processList.add(new RunningProcess("Idle", arrivalTime - processTime));
        processTime = arrivalTime;
      }

      processList.add(new RunningProcess("P" + nextJob.getId(), burstTime));
      usefulTime += burstTime;
      totWT += processTime - arrivalTime;
      processTime += burstTime;
    }

    totRT = totWT;
    totTAT = totWT + usefulTime;

    avgRT = avgWT = (double) totWT / (double) jobCount;
    avgTAT = (double) totTAT / (double) jobCount;

    utilization = usefulTime * 100.0 / processTime;
  }
  public static void solveOne() throws Exception {
    int n = nextInt();
    int m = nextInt();
    int k = nextInt();
    int w = nextInt();
    char[][][] levels = new char[k][n][];
    ;
    for (int i = 0; i < k; i++) {
      for (int j = 0; j < n; j++) {
        levels[i][j] = nextString().toCharArray();
      }
    }
    int[][] cost = new int[k][k];
    PriorityQueue<int[]> q =
        new PriorityQueue<>(
            k * k,
            new Comparator<int[]>() {
              @Override
              public int compare(int[] o1, int[] o2) {
                return o1[2] - o2[2];
              }
            });
    for (int i = 0; i < k; i++) {
      for (int j = i + 1; j < k; j++) {
        int[] cur = {i, j, diff(levels[i], levels[j]) * w};
        cost[i][j] = cur[2];
        q.add(cur);
        //              px("edge", cur);
      }
    }
    //      px(q.size());
    //      for (int[] e: cost) px(e);
    DisjointUnionSet djs = new DisjointUnionSet(k);
    boolean[][] al = new boolean[k][k];
    int finalCost = n * m * k;
    for (; q.size() > 0; ) {
      int[] edge = q.poll();
      int p1 = djs.getPartitionId(edge[0]);
      int p2 = djs.getPartitionId(edge[1]);
      //          px(edge, p1 == p2, edge[2]);
      if (edge[2] > n * m) break;
      if (p1 != p2) {

        djs.unionElement(edge[0], edge[1]);
        finalCost -= n * m - edge[2];
        al[edge[1]][edge[0]] = true;
        al[edge[0]][edge[1]] = true;
      }
    }
    //      for (boolean[] e: al) px(e);
    pn(finalCost);
    boolean[] ex = new boolean[k];
    for (int i = 0; i < k; i++) {
      if (!ex[i]) {
        dfs(i, -1, ex, k, al);
      }
    }
  }
Ejemplo n.º 26
0
 public List<int[]> getSkyline(int[][] buildings) {
   List<int[]> result = new ArrayList<>();
   if (buildings == null || buildings.length == 0) {
     return result;
   }
   Comparator<Point> comp =
       new Comparator<Point>() {
         @Override
         public int compare(Point a, Point b) {
           if (a.x != b.x) {
             return a.x - b.x;
           } else {
             return a.y - b.y;
           }
         }
       };
   PriorityQueue<Point> pq = new PriorityQueue<>(5, comp);
   for (int[] data : buildings) {
     pq.add(new Point(data[0], -data[2]));
     pq.add(new Point(data[1], data[2]));
   }
   TreeMap<Integer, Integer> map = new TreeMap<>();
   map.put(0, 1);
   int max = 0;
   while (!pq.isEmpty()) {
     Point cur = pq.poll();
     if (cur.y < 0) {
       if (!map.containsKey(-cur.y)) {
         map.put(-cur.y, 0);
       }
       map.put(-cur.y, map.get(-cur.y) + 1);
     } else {
       map.put(cur.y, map.get(cur.y) - 1);
       if (map.get(cur.y) == 0) {
         map.remove(cur.y);
       }
     }
     int curMax = map.lastEntry().getKey();
     if (curMax != max) {
       result.add(new int[] {cur.x, curMax});
       max = curMax;
     }
   }
   return result;
 }
 public TellerManager(ExecutorService e, CustomerLine customers, int adjustmentPeriod) {
   exec = e;
   this.customers = customers;
   this.adjustmentPeriod = adjustmentPeriod;
   // Start with a single teller:
   Teller teller = new Teller(customers);
   exec.execute(teller);
   workingTellers.add(teller);
 }
Ejemplo n.º 28
0
  public boolean resolve(LinkedList<Clause> clauses) {
    // Storing onto the stack to verify clauses in reverse order
    // LinkedList<Clause> expansionStack = new LinkedList<Clause>();
    PriorityQueue<Clause> expansionQueue =
        new PriorityQueue<Clause>(10000, new ClauseSizeComparator());

    for (int count = 0; count < clauses.size(); count++) {
      expansionQueue.add(clauses.get(count));
    }

    while (!expansionQueue.isEmpty()) // Until the stack is empty
    {

      Clause lastClause = expansionQueue.poll();

      for (int clauseCount = 0; clauseCount < lastClause.getClauseID() - 1; clauseCount++) {
        // If any new clauses are added since last execution
        // if(!clauses.getLast().equals(lastClause))
        {
          // break;
        }

        Clause tempClause = clauses.get(clauseCount);
        int numClausesBeforeExpansion = clauses.size();
        boolean result = lastClause.resolution(tempClause, clauses);

        if (!result) {
          return false;
        }

        int numClausesAfterExpansion = clauses.size();

        // System.out.println(numClausesAfterExpansion - numClausesBeforeExpansion); //Size does not
        // change

        // If new clauses are added, expand the newly added clause before expanding any other clause
        if (numClausesAfterExpansion - numClausesBeforeExpansion > 0) {
          expansionQueue.add(clauses.getLast());
        }
      }
    }

    return true;
  }
 public int findKthLargest(int[] nums, int k) { // o(n*log(k+1))
   PriorityQueue<Integer> largeK = new PriorityQueue<Integer>(k + 1); // min heap
   for (int e : nums) {
     largeK.add(e);
     if (largeK.size() > k) {
       largeK.poll(); // remove the least of k+1
     }
   }
   return largeK.poll(); // return the least of k
 }
Ejemplo n.º 30
0
 /**
  * 执行KNN算法,获取测试元组的类别
  *
  * @param list 训练数据集
  * @param test 测试元组
  * @param k 设定的K值
  * @return 测试元组的类别
  */
 public String knn(List<List<Double>> list, List<Double> test, int k) {
   PriorityQueue<KNNNode> pq = new PriorityQueue<KNNNode>(k, comparator);
   for (int i = 0; i < k; i++) {
     List<Double> trainTuple = list.get(i);
     Double c = trainTuple.get(0);
     KNNNode node = new KNNNode(i, getDistance(test, trainTuple), c);
     pq.add(node);
   }
   for (int i = 0; i < list.size(); i++) {
     List<Double> t = list.get(i);
     double distance = getDistance(test, t);
     KNNNode top = pq.peek();
     if (top.getDistance() > distance) {
       pq.remove();
       pq.add(new KNNNode(i, distance, t.get(0)));
     }
   }
   return getMostClass(pq);
 }