/** * Retrieves and removes the head of this queue, waiting if necessary until an element with an * expired delay is available on this queue, or the specified wait time expires. * * @return the head of this queue, or <tt>null</tt> if the specified waiting time elapses before * an element with an expired delay becomes available * @throws InterruptedException {@inheritDoc} */ public E poll(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { for (; ; ) { E first = q.peek(); if (first == null) { if (nanos <= 0) return null; else nanos = available.awaitNanos(nanos); } else { long delay = first.getDelay(TimeUnit.NANOSECONDS); if (delay <= 0) return q.poll(); if (nanos <= 0) return null; if (nanos < delay || leader != null) nanos = available.awaitNanos(nanos); else { Thread thisThread = Thread.currentThread(); leader = thisThread; try { long timeLeft = available.awaitNanos(delay); nanos -= delay - timeLeft; } finally { if (leader == thisThread) leader = null; } } } } } finally { if (leader == null && q.peek() != null) available.signal(); lock.unlock(); } }
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"); } }
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; }
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; }
public void testPriorityQueueDescending() { PriorityQueue pq = new PriorityQueue(false); try { pq.dequeue(); fail("NoSuchElementException not thrown on empty queue"); } catch (NoSuchElementException e) { } pq.enqueue("Test 2", 2); pq.enqueue("Test 1", 3); pq.enqueue("Test 3", 1); String peek1 = (String) pq.peek(); String s1 = (String) pq.dequeue(); String peek2 = (String) pq.peek(); String s2 = (String) pq.dequeue(); String s3 = (String) pq.dequeue(); try { pq.dequeue(); fail("NoSuchElementException not thrown on empty queue"); } catch (NoSuchElementException e) { } assertTrue("Peek #1 incorrect", peek1.equals("Test 1")); assertTrue("Peek #2 incorrect", peek2.equals("Test 2")); assertTrue("Dequeue #1 incorrect", s1.equals("Test 1")); assertTrue("Dequeue #2 incorrect", s2.equals("Test 2")); assertTrue("Dequeue #3 incorrect", s3.equals("Test 3")); }
/** * Retrieves and removes the head of this queue, waiting if necessary until an element with an * expired delay is available on this queue. * * @return the head of this queue * @throws InterruptedException {@inheritDoc} */ public E take() throws InterruptedException { final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { for (; ; ) { E first = q.peek(); if (first == null) available.await(); else { long delay = first.getDelay(TimeUnit.NANOSECONDS); if (delay <= 0) return q.poll(); else if (leader != null) available.await(); else { Thread thisThread = Thread.currentThread(); leader = thisThread; try { available.awaitNanos(delay); } finally { if (leader == thisThread) leader = null; } } } } } finally { if (leader == null && q.peek() != null) available.signal(); lock.unlock(); } }
public Integer findMedian() { if (min.size() < max.size()) { return max.peek(); } else if (max.size() < min.size()) { return min.peek(); } else { return ((max.peek() + min.peek()) / 2); } }
private void removeBuildings( PriorityQueue<Building> endings, PriorityQueue<Integer> heights, List<int[]> result) { final Building rm = endings.poll(); heights.remove(rm.height); while (endings.size() > 0 && endings.peek().to == rm.to) { heights.remove(endings.poll().height); } final int peek = heights.size() > 0 ? heights.peek() : 0; if (peek < rm.height) { result.add(new int[] {rm.to, peek}); } }
// 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(); }
/** * Retrieves and removes the head of this queue, waiting if necessary until an element with an * expired delay is available on this queue, or the specified wait time expires. * * @return the head of this queue, or <tt>null</tt> if the specified waiting time elapses before * an element with an expired delay becomes available * @throws InterruptedException {@inheritDoc} */ public E poll(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { for (; ; ) { E first = q.peek(); if (first == null) { if (nanos <= 0) return null; else nanos = available.awaitNanos(nanos); } else { long delay = first.getDelay(TimeUnit.NANOSECONDS); if (delay > 0) { if (nanos <= 0) return null; if (delay > nanos) delay = nanos; long timeLeft = available.awaitNanos(delay); nanos -= delay - timeLeft; } else { E x = q.poll(); assert x != null; if (q.size() != 0) available.signalAll(); return x; } } } } finally { lock.unlock(); } }
/** * 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); }
/** * Retrieves, but does not remove, the head of this queue, or returns <tt>null</tt> if this queue * is empty. Unlike <tt>poll</tt>, if no expired elements are available in the queue, this method * returns the element that will expire next, if one exists. * * @return the head of this queue, or <tt>null</tt> if this queue is empty. */ public E peek() { final ReentrantLock lock = this.lock; lock.lock(); try { return q.peek(); } finally { lock.unlock(); } }
public static String next() { if (pq.peek() != null) { System.out.println("queue pop"); String curUrl = pq.remove().url; if (!visitedUrl.contains(curUrl)) { visitedUrl.add(curUrl); return curUrl; } else return null; } else return null; }
public int[] maxSlidingWindow(int[] nums, int k) { int n = nums.length; if (n == 0) return new int[0]; PriorityQueue<Integer> pq = new PriorityQueue<>(k, Collections.reverseOrder()); Deque<Integer> queue = new ArrayDeque<>(); for (int i = 0; i < k; ++i) { add(pq, queue, nums[i]); } if (n == k) return new int[] {pq.poll().intValue()}; int[] max = new int[n - k + 1]; int idx = 0; for (int i = k; i < n; ++i) { max[idx++] = pq.peek().intValue(); pq.remove(queue.poll()); add(pq, queue, nums[i]); } max[idx] = pq.peek().intValue(); return max; }
/** * Retrieves and removes the head of this queue, or returns <tt>null</tt> if this queue has no * elements with an expired delay. * * @return the head of this queue, or <tt>null</tt> if this queue has no elements with an expired * delay */ public E poll() { final ReentrantLock lock = this.lock; lock.lock(); try { E first = q.peek(); if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0) return null; else return q.poll(); } finally { lock.unlock(); } }
public static void main(String[] args) { PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); pq.offer(6); pq.offer(-3); pq.offer(9); pq.offer(0); System.out.println(pq); while (pq.peek() != null) { System.out.print(pq.poll() + ", "); } System.out.println(); }
public static void main(String[] args) { PriorityQueue pq = new PriorityQueue(); // 下面代码依次向pq中加入四个元素 pq.offer(6); pq.offer(-3); pq.offer(9); pq.offer(0); // 输出pq队列,并不是按元素的加入顺序排列,而是按元素的大小顺序排列 System.out.println(pq); // 访问队列第一个元素,其实就是队列中最小的元素:-3 System.out.println(pq.peek()); }
/** * Inserts the specified element into this delay queue. * * @param e the element to add * @return <tt>true</tt> * @throws NullPointerException if the specified element is null */ public boolean offer(E e) { final ReentrantLock lock = this.lock; lock.lock(); try { E first = q.peek(); q.offer(e); if (first == null || e.compareTo(first) < 0) available.signalAll(); return true; } finally { lock.unlock(); } }
/* * As per [S. Koenig,2002] except for two main modifications: * 1. We stop planning after a number of steps, 'maxsteps' we do this * because this algorithm can plan forever if the start is surrounded by obstacles * 2. We lazily remove states from the open list so we never have to iterate through it. */ private int computeShortestPath() { LinkedList<State> s = new LinkedList<State>(); if (openList.isEmpty()) return 1; int k = 0; while ((!openList.isEmpty()) && (openList.peek().lt(s_start = calculateKey(s_start))) || (getRHS(s_start) != getG(s_start))) { if (k++ > maxSteps) { System.out.println("At maxsteps"); return -1; } State u; boolean test = (getRHS(s_start) != getG(s_start)); // lazy remove while (true) { if (openList.isEmpty()) return 1; u = openList.poll(); if (!isValid(u)) continue; if (!(u.lt(s_start)) && (!test)) return 2; break; } openHash.remove(u); State k_old = new State(u); if (k_old.lt(calculateKey(u))) { // u is out of date insert(u); } else if (getG(u) > getRHS(u)) { // needs update (got better) setG(u, getRHS(u)); s = getPred(u); for (State i : s) { updateVertex(i); } } else { // g <= rhs, state has got worse setG(u, Double.POSITIVE_INFINITY); s = getPred(u); for (State i : s) { updateVertex(i); } updateVertex(u); } } // while return 0; }
public void testPriorityQueueAscending() { PriorityQueue pq = new PriorityQueue(); try { pq.dequeue(); fail("NoSuchElementException not thrown on empty queue"); } catch (NoSuchElementException e) { } pq.enqueue("Test 2", 2); pq.enqueue("Test 3", 3); pq.enqueue("Test 1", 1); assertTrue("isEmpty is returned true on an nonempty queue", !pq.isEmpty()); String peek1 = (String) pq.peek(); String s1 = (String) pq.dequeue(); String peek2 = (String) pq.peek(); String s2 = (String) pq.dequeue(); String s3 = (String) pq.dequeue(); assertTrue("size was incorrect (should be 3)", pq.size() != 3); assertTrue("isEmpty is returned false on an empty queue", pq.isEmpty()); try { pq.dequeue(); fail("NoSuchElementException not thrown on empty queue"); } catch (NoSuchElementException e) { } assertTrue("Peek #1 incorrect", peek1.equals("Test 1")); assertTrue("Peek #2 incorrect", peek2.equals("Test 2")); assertTrue("Dequeue #1 incorrect", s1.equals("Test 1")); assertTrue("Dequeue #2 incorrect", s2.equals("Test 2")); assertTrue("Dequeue #3 incorrect", s3.equals("Test 3")); }
// 保存待访问的URL及其优先级 private static void SavePriorQueue(String filepath) throws Exception { BufferedWriter bw = new BufferedWriter(new FileWriter(filepath)); PriorityQueue<UrlValue> temp = new PriorityQueue<UrlValue>(); UrlValue cur = null; while (pq.peek() != null) { cur = pq.remove(); temp.offer(cur); bw.write(cur.url + " " + cur.value); bw.newLine(); } pq = temp; bw.flush(); bw.close(); }
public void getIndexInfo(String indexdir, int freqThreshold) { IndexReader reader = null; try { Directory dir = FSDirectory.open(new File(indexdir)); System.out.println(dir); reader = IndexReader.open(dir); System.out.println("document num:" + reader.numDocs()); System.out.println("======================"); TermEnum terms = reader.terms(); sortedTermQueue.clear(); maxDocNum = reader.maxDoc(); linkMap.clear(); termList.clear(); while (terms.next()) { // System.out.print(terms.term() + "\tDocFreq:" + TermDocs termDocs = reader.termDocs(terms.term()); MyTerm temp = new MyTerm(terms.term(), termDocs, maxDocNum); if (temp.totalFreq < freqThreshold) { continue; } /* * if(temp.originTrem.text().length()==1){ continue; } */ linkMap.put(temp.originTrem.text(), temp); sortedTermQueue.add(temp); termList.add(temp); } System.out.println("total Size:" + sortedTermQueue.size()); System.out.println("mapsize:" + linkMap.keySet().size()); // System.exit(0); int num = 0; this.maxFreq = sortedTermQueue.peek().totalFreq; while (!sortedTermQueue.isEmpty()) { num++; System.out.println(num + ":" + sortedTermQueue.poll()); } System.out.println("read index info done"); } catch (IOException e) { e.printStackTrace(); } finally { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } }
/** * Inserts the specified element into this delay queue. * * @param e the element to add * @return <tt>true</tt> * @throws NullPointerException if the specified element is null */ public boolean offer(E e) { final ReentrantLock lock = this.lock; lock.lock(); try { q.offer(e); if (q.peek() == e) { leader = null; available.signal(); } return true; } finally { lock.unlock(); } }
/** * Add a read to the manager * * @param read the read to add */ public void addRead(final GATKRead read) { if (read == null) throw new IllegalArgumentException("read added to manager is null, which is not allowed"); // if the new read is on a different contig or we have too many reads, then we need to flush the // queue and clear the map final boolean tooManyReads = getNReadsInQueue() >= MAX_RECORDS_IN_MEMORY; final boolean encounteredNewContig = getNReadsInQueue() > 0 && !waitingReads.peek().read.getContig().equals(read.getContig()); if (tooManyReads || encounteredNewContig) { if (DEBUG) logger.warn( "Flushing queue on " + (tooManyReads ? "too many reads" : ("move to new contig: " + read.getContig() + " from " + waitingReads.peek().read.getContig())) + " at " + read.getStart()); final int targetQueueSize = encounteredNewContig ? 0 : MAX_RECORDS_IN_MEMORY / 2; // write the required number of waiting reads to disk while (getNReadsInQueue() > targetQueueSize) writer.addRead(waitingReads.poll().read); } final SplitRead splitRead = new SplitRead(read); // fix overhangs, as needed for (final Splice splice : splices) fixSplit(splitRead, splice); // add the new read to the queue waitingReads.add(splitRead); }
/** * Retrieves and removes the head of this queue, or returns <tt>null</tt> if this queue has no * elements with an expired delay. * * @return the head of this queue, or <tt>null</tt> if this queue has no elements with an expired * delay */ public E poll() { final ReentrantLock lock = this.lock; lock.lock(); try { E first = q.peek(); if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0) return null; else { E x = q.poll(); assert x != null; if (q.size() != 0) available.signalAll(); return x; } } finally { lock.unlock(); } }
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; }
/** * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection<? super E> c) { if (c == null) throw new NullPointerException(); if (c == this) throw new IllegalArgumentException(); final ReentrantLock lock = this.lock; lock.lock(); try { int n = 0; for (; ; ) { E first = q.peek(); if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0) break; c.add(q.poll()); ++n; } return n; } finally { lock.unlock(); } }
public static void main(String[] args) { PriorityQueue<Person> queue = new PriorityQueue<Person>(10); // PriorityQueue<Person> queue = new PriorityQueue<Person>(10,new // ReverseComparable<Person>()); // PriorityQueue<Person> queue = new PriorityQueue<Person>(10,new Wealth()); // PriorityQueue<Person> queue = new PriorityQueue<Person>(10,new Age()); Person[] list = { new Person("A", 20, 100), new Person("C", 28, 200), new Person("E", 24, 50), new Person("B", 28, 50), new Person("D", 28, 100), new Person("F", 24, 100) }; for (Person p : list) queue.enqueue(p); System.out.println("Size = " + queue.size()); System.out.println("Första element: " + queue.peek()); while (!queue.empty()) System.out.println("Element: " + queue.dequeue() + ", size = " + queue.size()); }
/** * 执行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); }
/** * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection<? super E> c, int maxElements) { if (c == null) throw new NullPointerException(); if (c == this) throw new IllegalArgumentException(); if (maxElements <= 0) return 0; final ReentrantLock lock = this.lock; lock.lock(); try { int n = 0; while (n < maxElements) { E first = q.peek(); if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0) break; c.add(q.poll()); ++n; } if (n > 0) available.signalAll(); return n; } finally { lock.unlock(); } }