Java Code Examples for java.util.PriorityQueue#contains()

The following examples show how to use java.util.PriorityQueue#contains() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Dijkstra.java    From algos with MIT License 5 votes vote down vote up
public void shortestPath(int source, int destination) {
    Set<Node> visited = new HashSet<>();
    PriorityQueue<Node> pQueue = new PriorityQueue<>(new Comparator<Node>() {
        @Override
        public int compare(Node o1, Node o2) {
            return o1.cost - o2.cost;
        }
    });
    nodes[source].cost = 0;
    pQueue.add(nodes[source]);
    while(!pQueue.isEmpty()) {
        Node currVertex = pQueue.poll();
        for(int i = 0; i < graph.length; i++) {
            if(graph[currVertex.id][i]!=0 && !visited.contains(nodes[i]) ) {
                if(!pQueue.contains(nodes[i])) {
                    nodes[i].cost = currVertex.cost + graph[currVertex.id][i];
                    nodes[i].parent = currVertex;
                    pQueue.add(nodes[i]);
                }
                else {
                    nodes[i].cost = Math.min(nodes[i].cost, currVertex.cost + graph[currVertex.id][i]);
                    if(nodes[i].cost == currVertex.cost + graph[currVertex.id][i])
                        nodes[i].parent = currVertex;
                }
            }
        }
        visited.add(currVertex);
    }
}
 
Example 2
Source File: Solution.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 4 votes vote down vote up
public double[] medianSlidingWindow(int[] nums, int k) {
    int len = nums.length;
    int windowLen = len - k + 1;
    double[] res = new double[windowLen];
    PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
    PriorityQueue<Integer> minHeap = new PriorityQueue<>();
    // 下一个要填的值
    int next = 0;
    // 循环不变量:
    // 1、maxHeap 的堆顶小于等于 minHeap 的堆顶
    // 2、maxHeap.size() = minHeap.size() 或者
    // 3、maxHeap.size() = minHeap.size() + 1,这样中位数就在 maxHeap 的堆顶
    for (int i = 0; i < len; i++) {
        // 步骤 1:加入元素的时候,保持第 1、2、3 点
        maxHeap.add(nums[i]);
        minHeap.add(maxHeap.poll());
        if ((i & 1) == 0) {
            // 这个语义太难理解:
            // 如果还未添加 nums[i] 之前是偶数,那么添加 nums[i] 的效果是 maxHeap 多 1 个元素
            maxHeap.add(minHeap.poll());
        }
        // 步骤 2:移除窗口外的值,移除滑动窗口的左边界
        // 假设修正法:默认是大顶堆移除了一个元素
        if (i >= k) {
            int removeFrom = 1;
            // 如果不是在最小堆,就在最大堆
            if (minHeap.contains(nums[i - k])) {
                minHeap.remove(nums[i - k]);
                removeFrom = 0;
            } else {
                maxHeap.remove(nums[i - k]);
            }
            // 步骤 3:保持第 2、3 点
            if ((i & 1) == 1 && removeFrom == 1) {
                maxHeap.add(minHeap.poll());
            }
            if ((i & 1) == 0 && removeFrom == 0) {
                minHeap.add(maxHeap.poll());
            }
        }
        // 步骤 4:求滑动窗口的中位数
        if (i >= k - 1) {
            if (maxHeap.size() > minHeap.size()) {
                res[next] = maxHeap.peek();
            } else {
                res[next] = minHeap.peek() / 2.0 + maxHeap.peek() / 2.0;
            }
            next++;
        }
    }
    return res;
}
 
Example 3
Source File: CFDFinder.java    From metanome-algorithms with Apache License 2.0 4 votes vote down vote up
private PatternTableau generateTableau(final BitSet attributes, final int[][] values, final PositionListIndex lhs, final int[] rhs, final int numberOfTuples, final PruningStrategy pruningStrategy, final ExpansionStrategy expansionStrategy) {
	Pattern nullPattern = expansionStrategy.generateNullPattern(attributes);
	int violations = 0;
	List<IntArrayList> enrichedClusters = enrichPLI(lhs, numberOfTuples);
	for (IntArrayList cluster : enrichedClusters) {
		nullPattern.getCover().add(cluster.clone());
		violations += findViolationsFor(cluster, rhs);
	}
	nullPattern.setNumKeepers(numberOfTuples - violations);

	PriorityQueue<Pattern> frontier = new PriorityQueue<>();

	nullPattern.setSupport(nullPattern.getNumCover());
	frontier.add(nullPattern);

	Set<Pattern> T = new HashSet<>();

	while (!frontier.isEmpty() && !pruningStrategy.hasEnoughPatterns(T)) {
		Pattern currentPattern = frontier.poll();
		if (pruningStrategy.isPatternWorthAdding(currentPattern)) {
			T.add(currentPattern);
			pruningStrategy.addPattern(currentPattern);
			PriorityQueue<Pattern> newFrontier = new PriorityQueue<>();
			for (Pattern p : frontier) {
				p.updateCover(currentPattern);
				p.updateKeepers(rhs);
				if (pruningStrategy.isPatternWorthConsidering(p)) {
					newFrontier.add(p);
				}
			}
			frontier = newFrontier;
		} else {
			pruningStrategy.expandPattern(currentPattern);
			for (Pattern c : expansionStrategy.getChildPatterns(currentPattern)) {
				if (pruningStrategy.validForProcessing(c)) {
					pruningStrategy.processChild(c);
					List<IntArrayList> cover = determineCover(c, currentPattern, values);
					c.setCover(cover);
					c.updateKeepers(rhs);
					c.setSupport(c.getNumCover());
					if (pruningStrategy.isPatternWorthConsidering(c) && !frontier.contains(c)) {
						frontier.add(c);
					}
				}
			}
		}
	}
	return new PatternTableau(T, numberOfTuples);
}
 
Example 4
Source File: GraphCalculator.java    From charts with Apache License 2.0 4 votes vote down vote up
public NodeEdgeModel calculateClosenessCentrality(NodeEdgeModel nodeEdgeModel){
    PriorityQueue<GraphNode> queue = new PriorityQueue<>();

    ArrayList<GraphNode> visited = new ArrayList<>();
    int level;
    int counterUntilNextLevel;
    int counterOfNextLevel;
    double result;
    GraphNode currentNode;
    ArrayList<GraphNode> GraphNodes = nodeEdgeModel.getNodes();

    for(GraphNode node: GraphNodes){
        visited.clear();
        queue.clear();
        queue.add(node);
        result = 0;
        level = 0;
        counterUntilNextLevel = 1;
        counterOfNextLevel = 0;

        while(!queue.isEmpty()){
            currentNode = queue.poll();
            counterOfNextLevel += currentNode.getConnectedNodes().size();
            visited.add(currentNode);
            ArrayList<GraphNode> currentNodeList = new ArrayList<>(currentNode.getConnectedNodes());
            for(GraphNode gNode: currentNodeList){
                if(!visited.contains(gNode) && !queue.contains(gNode)){
                    queue.add(gNode);
                }
            }
            if(level>0) {
                result += 1.0 / (double) level;
            }
            counterUntilNextLevel--;
            if(counterUntilNextLevel == 0){
                level++;
                counterUntilNextLevel = counterOfNextLevel;
                counterOfNextLevel = 0;
            }
        }
        node.setNumericAttribute(closenessKey, new Double(result));
    }
    return nodeEdgeModel;
}
 
Example 5
Source File: MinIndexedBinaryHeapTest.java    From Algorithms with MIT License 4 votes vote down vote up
@Test
public void testRandomInsertionsAndRemovals() {
  for (int n = 1; n < 500; n++) {
    List<Integer> indexes = genUniqueRandList(n);
    MinIndexedBinaryHeap<Integer> pq1 = new MinIndexedBinaryHeap<Integer>(n);
    PriorityQueue<Integer> pq2 = new PriorityQueue<Integer>(n);
    List<Integer> indexesToRemove = new ArrayList<>();

    final double p = Math.random();
    for (int i = 0; i < n; i++) {
      int ii = indexes.get(i);
      pq1.insert(ii, ii);
      pq2.add(ii);
      indexesToRemove.add(ii);
      assertThat(pq1.isMinHeap()).isTrue();

      if (Math.random() < p) {
        int itemsToRemove = (int) (Math.random() * 10);
        while (itemsToRemove-- > 0 && indexesToRemove.size() > 0) {
          int iii = (int) (Math.random() * indexesToRemove.size());
          int indexToRemove = indexesToRemove.get(iii);
          boolean contains1 = pq1.contains(indexToRemove);
          boolean contains2 = pq2.contains(indexToRemove);
          assertThat(contains1).isEqualTo(contains2);
          assertThat(pq1.isMinHeap()).isTrue();
          if (contains2) {
            pq1.delete(indexToRemove);
            pq2.remove(indexToRemove);
            indexesToRemove.remove(iii);
          }
          if (!pq2.isEmpty()) assertThat(pq1.peekMinValue()).isEqualTo(pq2.peek());
        }
      }

      for (int index : indexesToRemove) {
        assertThat(pq2.contains(index)).isTrue(); // Sanity check.
        assertThat(pq1.contains(index)).isTrue();
      }

      assertThat(pq1.size()).isEqualTo(pq2.size());
      assertThat(pq1.isEmpty()).isEqualTo(pq2.isEmpty());
      if (!pq2.isEmpty()) assertThat(pq1.peekMinValue()).isEqualTo(pq2.peek());
    }
  }
}
 
Example 6
Source File: MinIndexedBinaryHeapTest.java    From data-structures with MIT License 4 votes vote down vote up
@Test
public void testRandomInsertionsAndRemovals() {
  for (int n = 1; n < 500; n++) {
    List<Integer> indexes = genUniqueRandList(n);
    MinIndexedBinaryHeap<Integer> pq1 = new MinIndexedBinaryHeap<Integer>(n);
    PriorityQueue<Integer> pq2 = new PriorityQueue<Integer>(n);
    List<Integer> indexesToRemove = new ArrayList<>();

    final double p = Math.random();
    for (int i = 0; i < n; i++) {
      int ii = indexes.get(i);
      pq1.insert(ii, ii);
      pq2.add(ii);
      indexesToRemove.add(ii);
      assertThat(pq1.isMinHeap()).isTrue();

      if (Math.random() < p) {
        int itemsToRemove = (int) (Math.random() * 10);
        while (itemsToRemove-- > 0 && indexesToRemove.size() > 0) {
          int iii = (int) (Math.random() * indexesToRemove.size());
          int indexToRemove = indexesToRemove.get(iii);
          boolean contains1 = pq1.contains(indexToRemove);
          boolean contains2 = pq2.contains(indexToRemove);
          assertThat(contains1).isEqualTo(contains2);
          assertThat(pq1.isMinHeap()).isTrue();
          if (contains2) {
            pq1.delete(indexToRemove);
            pq2.remove(indexToRemove);
            indexesToRemove.remove(iii);
          }
          if (!pq2.isEmpty()) assertThat(pq1.peekMinValue()).isEqualTo(pq2.peek());
        }
      }

      for (int index : indexesToRemove) {
        assertThat(pq2.contains(index)).isTrue(); // Sanity check.
        assertThat(pq1.contains(index)).isTrue();
      }

      assertThat(pq1.size()).isEqualTo(pq2.size());
      assertThat(pq1.isEmpty()).isEqualTo(pq2.isEmpty());
      if (!pq2.isEmpty()) assertThat(pq1.peekMinValue()).isEqualTo(pq2.peek());
    }
  }
}
 
Example 7
Source File: QueueManager.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Checks whether a procedure is in the queue
 *
 * @param queue        the queue to check
 * @param procedureUri the procedure look for
 * @return true if the procedure was in the queue and updated
 */
public static boolean isInQueue(PriorityQueue<Uri> queue, Uri procedureUri) {
    return queue.contains(procedureUri);
}