java.util.ArrayDeque#removeLast ( )源码实例Demo

下面列出了java.util.ArrayDeque#removeLast ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

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;
}
 
源代码2 项目: openjdk-jdk9   文件: PartialEscapeClosure.java
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);
                        }
                    }
                }
            }
        }
    }
}
 
源代码3 项目: util   文件: PosixFileOperations.java
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();
}
 
源代码4 项目: RichEditorView   文件: LuBottomMenu.java
/**
 * @param pathRecord 点击的展开路径记录
 *                   通过路径直接恢复视图序列
 */
private void restoreAllInfo(ArrayDeque<MenuItem> pathRecord) {
    mPathRecord.clear();
    while (!pathRecord.isEmpty()) {
        mCurMenuItem = pathRecord.getLast();
        addOneLevel();
        pathRecord.removeLast();
    }

}
 
源代码5 项目: cloud-opensource-java   文件: LinkageCheckTask.java
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();
}
 
源代码6 项目: Android-Cheat-sheet   文件: Dequeue.java
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()] + " ");
    }
}
 
源代码7 项目: openjdk-jdk9   文件: ArrayDequeTest.java
/**
 * 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());
}
 
源代码8 项目: copybara   文件: Glob.java
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);
}
 
源代码9 项目: megamek   文件: LongestPathFinder.java
/**
 * 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;
}
 
/**
 * 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;
}
 
源代码11 项目: j2objc   文件: ArrayDequeTest.java
/**
 * 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());
}
 
源代码12 项目: MediaSDK   文件: Converter.java
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;
}
 
源代码13 项目: JImageHash   文件: BinaryTree.java
/**
 * 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;
}
 
源代码14 项目: rdf4j   文件: Models.java
/**
 * 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();
		}

	}

}
 
源代码15 项目: Any-Angle-Pathfinding   文件: KeyToggler.java
private GridObjects peekSecondLast(ArrayDeque<GridObjects> list) {
    GridObjects top = list.removeLast();
    GridObjects peek = list.peekLast();
    list.addLast(top);
    return peek;
}
 
源代码16 项目: Cubes   文件: ChatActor.java
private void trim(ArrayDeque<ChatMessage> messages, int maxLength) {
  while (messages.size() > maxLength) {
    messages.removeLast();
  }
}