Java Code Examples for java.util.ArrayDeque#removeLast()

The following examples show how to use java.util.ArrayDeque#removeLast() . 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: Solution5.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
public int[] maxSlidingWindow(int[] nums, int k) {
    int len = nums.length;
    if (len == 0) {
        return new int[0];
    }
    int[] res = new int[len - k + 1];
    ArrayDeque<Integer> queue = new ArrayDeque<>(len);
    for (int i = 0; i < len; i++) {
        // 左边界滑出
        if (i >= k && queue.getFirst() == i - k) {
            queue.removeFirst();
        }

        // 在 nums[i] 加入之前考虑把不可能的值弹出
        while (!queue.isEmpty() && nums[queue.getLast()] <= nums[i]) {
            queue.removeLast();
        }

        queue.add(i);
        // 记录结果
        if (i >= k - 1) {
            res[i - k + 1] = nums[queue.getFirst()];
        }
    }
    return res;
}
 
Example 2
Source File: PartialEscapeClosure.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void collectReferencedVirtualObjects(BlockT state, Set<VirtualObjectNode> virtual) {
    ArrayDeque<VirtualObjectNode> queue = new ArrayDeque<>(virtual);
    while (!queue.isEmpty()) {
        VirtualObjectNode object = queue.removeLast();
        int id = object.getObjectId();
        if (id != -1) {
            ObjectState objState = state.getObjectStateOptional(id);
            if (objState != null && objState.isVirtual()) {
                for (ValueNode entry : objState.getEntries()) {
                    if (entry instanceof VirtualObjectNode) {
                        VirtualObjectNode entryVirtual = (VirtualObjectNode) entry;
                        if (!virtual.contains(entryVirtual)) {
                            virtual.add(entryVirtual);
                            queue.addLast(entryVirtual);
                        }
                    }
                }
            }
        }
    }
}
 
Example 3
Source File: PosixFileOperations.java    From util with Apache License 2.0 6 votes vote down vote up
public static String relativePath(File base, File path) {
    ArrayDeque<String> baseParts = getParts(base);
    ArrayDeque<String> pathParts = getParts(path);
    StringBuilder ret = new StringBuilder();
    while (!baseParts.isEmpty() && !pathParts.isEmpty() && baseParts.getLast().equals(pathParts.getLast())) {
        baseParts.removeLast();
        pathParts.removeLast();
    }
    while (!baseParts.isEmpty()) {
        ret.append("..");
        ret.append(separator);
        baseParts.removeLast();
    }
    while (!pathParts.isEmpty()) {
        String part = pathParts.removeLast();
        ret.append(part);
        if (!pathParts.isEmpty()) ret.append(separator);
    }
    return ret.toString();
}
 
Example 4
Source File: LuBottomMenu.java    From RichEditorView with Apache License 2.0 5 votes vote down vote up
/**
 * @param pathRecord 点击的展开路径记录
 *                   通过路径直接恢复视图序列
 */
private void restoreAllInfo(ArrayDeque<MenuItem> pathRecord) {
    mPathRecord.clear();
    while (!pathRecord.isEmpty()) {
        mCurMenuItem = pathRecord.getLast();
        addOneLevel();
        pathRecord.removeLast();
    }

}
 
Example 5
Source File: LinkageCheckTask.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
private void recordDependencyPaths(
    ImmutableListMultimap.Builder<String, String> output,
    ArrayDeque<ResolvedComponentResult> stack,
    ImmutableSet<String> targetCoordinates) {
  ResolvedComponentResult item = stack.getLast();
  ModuleVersionIdentifier identifier = item.getModuleVersion();
  String coordinates =
      String.format(
          "%s:%s:%s", identifier.getGroup(), identifier.getName(), identifier.getVersion());
  if (targetCoordinates.contains(coordinates)) {
    String dependencyPath =
        stack.stream().map(this::formatComponentResult).collect(Collectors.joining(" / "));
    output.put(coordinates, dependencyPath);
  }

  for (DependencyResult dependencyResult : item.getDependencies()) {
    if (dependencyResult instanceof ResolvedDependencyResult) {
      ResolvedDependencyResult resolvedDependencyResult =
          (ResolvedDependencyResult) dependencyResult;
      ResolvedComponentResult child = resolvedDependencyResult.getSelected();
      stack.add(child);
      recordDependencyPaths(output, stack, targetCoordinates);
    } else if (dependencyResult instanceof UnresolvedDependencyResult) {
      UnresolvedDependencyResult unresolvedResult = (UnresolvedDependencyResult) dependencyResult;
      getLogger()
          .error(
              "Could not resolve dependency: "
                  + unresolvedResult.getAttempted().getDisplayName());
    } else {
      throw new IllegalStateException("Unexpected dependency result type: " + dependencyResult);
    }
  }

  stack.removeLast();
}
 
Example 6
Source File: Dequeue.java    From Android-Cheat-sheet with Apache License 2.0 5 votes vote down vote up
public static void findMaximumSlidingWindow(int[] arr,
                                            int windowSize) {
    if (arr.length < windowSize) return;

    ArrayDeque<Integer> list = new ArrayDeque();
    for (int i = 0; i < windowSize; i++) {

        while (!list.isEmpty() && arr[i] >= arr[list.peekLast()]) {
            list.removeLast();
        }
        list.addLast(i);
    }

    System.out.print(arr[list.peekFirst()] + " ");


    for (int i = windowSize; i < arr.length; i++) {

        while (!list.isEmpty() && arr[i] >= arr[list.peekLast()]) {
            list.removeLast();
        }

        if (!list.isEmpty() && list.peekFirst() <= i - windowSize) {
            list.removeFirst();
        }

        list.addLast(i);
        System.out.print(arr[list.peekFirst()] + " ");
    }
}
 
Example 7
Source File: ArrayDequeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * removeLast() removes last element, or throws NSEE if empty
 */
public void testRemoveLast() {
    ArrayDeque q = populatedDeque(SIZE);
    for (int i = SIZE - 1; i >= 0; --i) {
        assertEquals(i, q.removeLast());
    }
    try {
        q.removeLast();
        shouldThrow();
    } catch (NoSuchElementException success) {}
    assertNull(q.peekLast());
}
 
Example 8
Source File: Glob.java    From copybara with Apache License 2.0 5 votes vote down vote up
static ImmutableSet<String> computeRootsFromIncludes(Iterable<String> includes) {
  List<String> roots = new ArrayList<>();

  for (String includePath : includes) {
    ArrayDeque<String> components = new ArrayDeque<>();
    for (String component : Splitter.on('/').split(includePath)) {
      components.add(unescape(component));
      if (isMeta(component)) {
        break;
      }
    }
    components.removeLast();
    if (components.isEmpty()) {
      return ImmutableSet.of("");
    }
    roots.add(Joiner.on('/').join(components));
  }

  // Remove redundant roots - e.g. "foo" covers all paths that start with "foo/"
  Collections.sort(roots);
  int r = 0;
  while (r < roots.size() - 1) {
    if (roots.get(r + 1).startsWith(roots.get(r) + "/")) {
      roots.remove(r + 1);
    } else {
      r++;
    }
  }

  return ImmutableSet.copyOf(roots);
}
 
Example 9
Source File: LongestPathFinder.java    From megamek with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the longest move path to a hex at given coordinates. If multiple
 * paths reach coords with different final facings, the best one is chosen.
 * If none paths are present then {@code null} is returned.
 *
 * @param coords - the coordinates of the hex
 * @return the shortest move path to hex at given coordinates
 */
public MovePath getComputedPath(Coords coords) {
    Deque<MovePath> q = getCost(coords, new Comparator<Deque<MovePath>>() {
        @Override
        public int compare(Deque<MovePath> q1, Deque<MovePath> q2) {
            MovePath mp1 = q1.getLast(), mp2 = q2.getLast();
            int t = mp2.getHexesMoved() - mp1.getHexesMoved();
            if (t != 0) {
                return t;
            } else {
                return mp1.getMpUsed() - mp2.getMpUsed();
            }
        }
    });
    if (q != null) {
        if (!aero) {
            return q.getLast();
        } else {
            ArrayDeque<MovePath> tq = new ArrayDeque<>(q);
            MovePath mp = tq.removeLast();
            while (!tq.isEmpty()) {
                MovePath qlast = tq.removeLast();
                if (mp.getHexesMoved() == qlast.getHexesMoved() && mp.getMpUsed() > qlast.getMpUsed()) {
                    mp = qlast;
                } else {
                    break;
                }
            }
            return mp;
        }
    } else
        return null;
}
 
Example 10
Source File: MaxInAllSubArrays.java    From Algorithms-and-Data-Structures-in-Java with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Finds the maximum element in each and every sub-array
 * in {@param a} of size {@param k}.
 * <p>
 * Time complexity: O(n)
 * Auxiliary Space: O(k)
 *
 * @param a
 * @param k
 * @return
 */
public static int[] maxInAllSubArraysOfSizeK(int[] a, int k) {
    int i, j = 0;
    int[] result = new int[a.length - k + 1];
    /**
     * Create a Double Ended Queue, Qi that will store indexes of array elements
     * The queue will store indexes of useful elements in every window and it will
     * maintain decreasing order of values from front to rear in Qi, i.e, 
     * arr[Qi.front[]] to arr[Qi.rear()] are sorted in decreasing order.
     */
    ArrayDeque<Integer> deque = new ArrayDeque<>();

    for (i = 0; i < k; i++) {
        // remove smaller elements on left side of current element
        while (!deque.isEmpty() && a[i] > a[deque.peekLast()]) {
            deque.removeLast();
        }
        deque.addLast(i);
    }

    for (; i < a.length; i++) {
        result[j++] = a[deque.peekFirst()];

        // remove elements that are outside window k
        while (!deque.isEmpty() && deque.peekFirst() <= i - k) {
            deque.removeFirst();
        }
        // remove smaller elements on left side of current element
        while (!deque.isEmpty() && a[i] > a[deque.peekLast()]) {
            deque.removeLast();
        }
        deque.addLast(i);
    }

    // for max in last k elements
    result[j] = a[deque.peekFirst()];

    return result;
}
 
Example 11
Source File: ArrayDequeTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * removeLast() removes last element, or throws NSEE if empty
 */
public void testRemoveLast() {
    ArrayDeque q = populatedDeque(SIZE);
    for (int i = SIZE - 1; i >= 0; --i) {
        assertEquals(i, q.removeLast());
    }
    try {
        q.removeLast();
        shouldThrow();
    } catch (NoSuchElementException success) {}
    assertNull(q.peekLast());
}
 
Example 12
Source File: Converter.java    From MediaSDK with Apache License 2.0 4 votes vote down vote up
private <T> boolean search(MimedType<T> target, ArrayDeque<PathInfo> bestMatch, ArrayDeque<PathInfo> currentPath, MimedType currentSearch, HashSet<MimedType> searched) {
    if (target.isTypeOf(currentSearch)) {
        bestMatch.clear();
        bestMatch.addAll(currentPath);
        return true;
    }

    // the current path must have potential to be better than the best match
    if (!bestMatch.isEmpty() && PathInfo.distance(currentPath) >= PathInfo.distance(bestMatch))
        return false;

    // prevent reentrancy
    if (searched.contains(currentSearch))
        return false;

    boolean found = false;
    searched.add(currentSearch);
    ConverterTransformers<Object, Object> converterTransformers = outputs.getAll(currentSearch);
    for (MimedType candidate: converterTransformers.keySet()) {
        // this simulates the mime results of a transform
        MimedType newSearch = new MimedType(candidate.type, mimeReplace(currentSearch.mime, candidate.mime));

        PathInfo path = new PathInfo();
        path.transformer = converterTransformers.get(candidate);
        path.mime = newSearch.mime;
        path.candidate = candidate;
        currentPath.addLast(path);
        try {
            found |= search(target, bestMatch, currentPath, newSearch, searched);
        }
        finally {
            currentPath.removeLast();
        }
    }

    if (found) {
        // if this resulted in a success,
        // clear this from the currentSearch list, because we know this leads
        // to a potential solution. maybe we can arrive here faster.
        searched.remove(currentSearch);
    }

    return found;
}
 
Example 13
Source File: BinaryTree.java    From JImageHash with MIT License 4 votes vote down vote up
/**
 * Retrieve the hash that is the most similar to the queried hash. The closest
 * hash is the hash with the smallest distance.
 * 
 * @param hash to search the neighbor for.
 * @return the closest hash saved in this tree.
 * @since 3.0.0
 */
@Override
public List<Result<T>> getNearestNeighbour(Hash hash) {

	if (ensureHashConsistency && algoId != hash.getAlgorithmId()) {
		throw new IllegalStateException("Tried to add an incompatible hash to the binary tree");
	}

	BigInteger hashValue = hash.getHashValue();
	int treeDepth = hash.getBitResolution();

	ArrayDeque<NodeInfo<T>> queue = new ArrayDeque<>();

	List<Result<T>> result = new ArrayList<>();

	double curBestDistance = Double.MAX_VALUE;

	// Depth first search with aggressive pruning

	// Begin search at the root
	queue.add(new NodeInfo<T>(root, 0, treeDepth));

	while (!queue.isEmpty()) {

		NodeInfo<T> info = queue.removeLast();

		// If we found a better result ignore it.
		if (info.distance > curBestDistance) {
			continue;
		}

		// We reached a leaf
		if (info.depth == 0) {

			if (curBestDistance > info.distance) {
				result.clear();
				curBestDistance = info.distance;
			}
			@SuppressWarnings("unchecked")
			Leaf<T> leaf = (Leaf<T>) info.node;
			for (T o : leaf.getData()) {
				result.add(new Result<T>(o, info.distance, info.distance / (double) treeDepth));
			}
			continue;
		}

		// TODO das ist keine tiefensuche!

		// Next bit
		boolean bit = hashValue.testBit(info.depth - 1);
		// Are children of the current

		if (info.distance + 1 <= curBestDistance) {
			Node failedChild = info.node.getChild(!bit);
			// Maybe the child does not exist
			if (failedChild != null) {
				queue.add(new NodeInfo<T>(failedChild, info.distance + 1, info.depth - 1));
			}
		}

		Node correctChild = info.node.getChild(bit);
		if (correctChild != null) {
			queue.add(new NodeInfo<T>(correctChild, info.distance, info.depth - 1));
		}

	}
	return result;
}
 
Example 14
Source File: Models.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * A recursive method for finding a complete mapping between blank nodes in model1 and blank nodes in model2. The
 * algorithm does a depth-first search trying to establish a mapping for each blank node occurring in model1.
 *
 * @param model1
 * @param model2
 * @return true if a complete mapping has been found, false otherwise.
 */
private static boolean matchModels(final List<? extends Statement> model1, final Model model2) {

	ArrayDeque<Iterator<Statement>> iterators = new ArrayDeque<>();
	ArrayDeque<Map<Resource, Resource>> bNodeMappings = new ArrayDeque<>();

	Map<Resource, Resource> bNodeMapping = Collections.emptyMap();
	int idx = 0;

	Iterator<Statement> iterator = null;
	while (true) {

		if (idx >= model1.size()) {
			return true;
		}

		Statement st1 = model1.get(idx);

		if (iterator == null) {

			List<Statement> matchingStats = findMatchingStatements(st1, model2, bNodeMapping);

			iterator = matchingStats.iterator();
		}

		if (iterator.hasNext()) {
			Statement st2 = iterator.next();

			// Map bNodes in st1 to bNodes in st2
			Map<Resource, Resource> newBNodeMapping = createNewBnodeMapping(bNodeMapping, st1, st2);

			iterators.addLast(iterator);
			bNodeMappings.addLast(bNodeMapping);

			iterator = null;

			bNodeMapping = newBNodeMapping;
			idx++;

		}

		if (iterator != null) {
			idx--;
			if (idx < 0) {
				return false;
			}
			iterator = iterators.removeLast();
			bNodeMapping = bNodeMappings.removeLast();
		}

	}

}
 
Example 15
Source File: KeyToggler.java    From Any-Angle-Pathfinding with The Unlicense 4 votes vote down vote up
private GridObjects peekSecondLast(ArrayDeque<GridObjects> list) {
    GridObjects top = list.removeLast();
    GridObjects peek = list.peekLast();
    list.addLast(top);
    return peek;
}
 
Example 16
Source File: ChatActor.java    From Cubes with MIT License 4 votes vote down vote up
private void trim(ArrayDeque<ChatMessage> messages, int maxLength) {
  while (messages.size() > maxLength) {
    messages.removeLast();
  }
}