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

The following examples show how to use java.util.Deque#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: Solution1.java    From code with Apache License 2.0 6 votes vote down vote up
/**
 * 题目地址:https://leetcode-cn.com/problems/hua-dong-chuang-kou-de-zui-da-zhi-lcof/
 * -------------------------------------------------------------------
 * 思考:
 * -------------------------------------------------------------------
 * 思路:单调队列
 *
 *
 * -------------------------------------------------------------------
 * 时间复杂度:
 * 空间复杂度:
 */
public int[] maxSlidingWindow(int[] nums, int k) {
    if (nums == null || nums.length == 0)
        return nums;

    Deque<Integer> deque = new ArrayDeque<>();
    int[] ans = new int[nums.length - k + 1];

    for (int i = 0; i < nums.length; i++) {
        int index = i + 1 - k;
        if (!deque.isEmpty() && deque.peekFirst() < index) {
            deque.removeFirst();//deque最大值不在滑动窗口中
        }
        while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) {
            deque.removeLast();//新进入窗口的值大于deque最小值
        }
        deque.addLast(i);
        if (index >= 0) {//第一个窗口装满
            ans[index] = nums[deque.peekFirst()];
        }
    }
    return ans;
}
 
Example 2
Source File: Solution3.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
private void dfs(String s, int len, int start, int splitTimes, Deque<String> pre, List<String> res) {
    if (start == len) {
        if (splitTimes == 4) {
            res.add(String.join(".", pre));
        }
        return;
    }

    for (int i = 0; i < 3; i++) {
        if (start + i >= len){
            break;
        }

        if (judgeStringIfIpNum(s,start,start + i)) {
            String currentNum = s.substring(start, start + i + 1);
            pre.addLast(currentNum);
            dfs(s, len,start + i + 1, splitTimes + 1, pre,res);
            pre.removeLast();
        }
    }
}
 
Example 3
Source File: Solution3.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
private void dfs(TreeNode node, int sum, Deque<Integer> path, List<List<Integer>> res) {
    if (node == null) {
        return;
    }
    if (node.val == sum && node.left == null && node.right == null) {
        path.addLast(node.val);
        res.add(new ArrayList<>(path));
        path.removeLast();
        return;
    }

    path.addLast(node.val);
    dfs(node.left, sum - node.val, path, res);
    dfs(node.right, sum - node.val, path, res);
    path.removeLast();
}
 
Example 4
Source File: Solution.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
public int[] reversePrint(ListNode head) {
    if (head == null) {
        return new int[0];
    }

    // Java 在 Stack 类的文档里建议使用 Deque
    Deque<Integer> stack = new ArrayDeque<>();
    ListNode curNode = head;
    while (curNode != null) {
        stack.addLast(curNode.val);
        curNode = curNode.next;
    }


    int size = stack.size();
    int[] res = new int[size];
    for (int i = 0; i < size; i++) {
        // 这里因为提前读取了 size,因此在 stack 发送 pop 的时候,
        // 不必检测 stack 是否为空
        res[i] = stack.removeLast();
    }
    return res;
}
 
Example 5
Source File: DagChecker.java    From sql-layer with GNU Affero General Public License v3.0 6 votes vote down vote up
private boolean tryAdd(Set<? extends T> roots, Graph<T, Pair> graph, Set<T> knownNodes,
                       CycleDetector<T, Pair> cycleDetector, Deque<T> nodePath)
{
    for (T node : roots) {
        nodePath.addLast(node);
        graph.addVertex(node);
        if (knownNodes.add(node)) {
            Set<? extends T> nodesFrom = nodesFrom(node);
            for (T from : nodesFrom) {
                graph.addVertex(from);
                Pair edge = new Pair(from, node);
                graph.addEdge(from, node, edge);
                nodePath.addLast(from);
                if (cycleDetector.detectCycles())
                    return false;
                nodePath.removeLast();
            }
            if (!tryAdd(nodesFrom, graph, knownNodes, cycleDetector, nodePath))
                return false;
        }
        nodePath.removeLast();
    }
    return true;
}
 
Example 6
Source File: Solution3.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
public int[] dailyTemperatures(int[] T) {
    int len = T.length;

    int[] newT = new int[len + 1];
    newT[0] = Integer.MAX_VALUE;
    for (int i = 0; i < len; i++) {
        newT[i + 1] = T[i];
    }

    int[] res = new int[len];
    T = newT;

    Deque<Integer> stack = new ArrayDeque<>();
    stack.addLast(0);

    // 注意有效位置从 1 开始
    for (int i = 1; i <= len; i++) {
        // 由于有哨兵结点在,查看栈顶元素的时候不用判空
        while (T[stack.peekLast()] < T[i]) {
            Integer top = stack.removeLast();
            res[top - 1] = i - top;
        }
        stack.addLast(i);
    }
    return res;
}
 
Example 7
Source File: Solution5.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
private void dfs(int[] nums, int len,
                 int maxCount, int begin,
                 Deque<Integer> path,
                 List<List<Integer>> res) {
    if (maxCount == path.size()) {
        res.add(new ArrayList<>(path));
        return;
    }
    for (int i = begin; i < len; i++) {
        // 包括当前这个元素
        path.addLast(nums[i]);
        dfs(nums, len, maxCount, i + 1, path, res);
        // 不包括当前这个元素
        path.removeLast();
    }
}
 
Example 8
Source File: Solution.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
private void dfs(int n, int k, int begin, Deque<Integer> path, List<List<Integer>> res) {
    if (path.size() == k) {
        // 够数了,就添加到结果集中
        res.add(new ArrayList<>(path));
        return;
    }
    // 关键在于分析出 i 的上界
    for (int i = begin; i <= n; i++) {
        path.addLast(i);
        dfs(n, k, i + 1, path, res);
        path.removeLast();
    }
}
 
Example 9
Source File: Solution6.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
private void dfs(int[] nums, int start, int depth, Deque<Integer> stack, List<List<Integer>> res) {
    if (depth == stack.size()) {
        res.add(new ArrayList<>(stack));
        return;
    }
    for (int i = start; i < nums.length; i++) {
        stack.addLast(nums[i]);
        dfs(nums, i + 1, depth, stack, res);
        stack.removeLast();
    }
}
 
Example 10
Source File: CheckedConfig.java    From night-config with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void recursiveCheck(Deque<String> path, Object value) {
	if (value instanceof Config) {
		for (Config.Entry entry : ((Config)value).entries()) {
			path.addLast(entry.getKey());
			recursiveCheck(path, entry.getValue());
			path.removeLast();
		}
	} else {
		String[] arr = (String[])path.toArray();
		checker.checkUpdate(StandardAttributes.VALUE, arr, value, value);
	}
}
 
Example 11
Source File: Solution5.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
private void dfs(int residue, int start, Deque<Integer> stack) {
    if (residue == 0) {
        res.add(new ArrayList<>(stack));
        return;
    }
    for (int i = start; i < len && residue - candidates[i] >= 0; i++) {
        stack.addLast(candidates[i]);
        dfs(residue - candidates[i], i, stack);
        stack.removeLast();
    }
}
 
Example 12
Source File: BuildChainBuilder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void cycleCheckProduce(Set<Produce> produceSet, Set<BuildStepBuilder> visited, Set<BuildStepBuilder> checked,
        final Map<BuildStepBuilder, Set<Produce>> dependencies, final Deque<Produce> producedPath)
        throws ChainBuildException {
    for (Produce produce : produceSet) {
        producedPath.add(produce);
        cycleCheck(produce.getStepBuilder(), visited, checked, dependencies, producedPath);
        producedPath.removeLast();
    }
}
 
Example 13
Source File: Solution2.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
/**
 * @param nums
 * @param begin
 * @param len
 * @param path
 * @param res
 */
private void dfs(int[] nums, int begin, int len, Deque<Integer> path, List<List<Integer>> res) {
    // 在遍历的过程中,收集符合条件的结果
    res.add(new ArrayList<>(path));
    for (int i = begin; i < len; i++) {
        path.addLast(nums[i]);
        dfs(nums, i + 1, len, path, res);
        path.removeLast();
    }
}
 
Example 14
Source File: LeetCode93.java    From Project with Apache License 2.0 5 votes vote down vote up
public void splitIP(String s, int sLength, int residueSplitTimes, int beginIndex,
                    Deque<String> path, List<String> resList) {
    // 如果划分到结尾了,并且划分了 4 段,则返回
    if (beginIndex == sLength) {
        if (residueSplitTimes == 0) {
            resList.add(String.join(".", path));
        }
        return;
    }

    // 因为每一次划分都有三种可能性,一位,两位、三位
    for (int i = beginIndex; i < beginIndex + 3; i++) {
        if (i >= sLength) {
            break;
        }
        if (residueSplitTimes * 3 < sLength - i) {
            continue;
        }

        // 看上面三种划分是否结果能够构成 IP, 如果可以就是一种可能性,可以继续划分
        if (judgeIfIpSegment(s, beginIndex, i)) {
            String curIPSegment = s.substring(beginIndex, i + 1);
            path.addLast(curIPSegment);
            splitIP(s, sLength, residueSplitTimes - 1, i + 1, path, resList);
            path.removeLast();
        }
    }
}
 
Example 15
Source File: Solution2.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
public boolean isSymmetric(TreeNode root) {
    if (root == null) {
        return true;
    }

    // 实现类不能选用 ArrayDeque,因为该类的 add 方法会对添加的元素做非空检查
    Deque<TreeNode> deque = new LinkedList<>();
    // Deque<TreeNode> deque = new ArrayDeque<>();

    deque.addFirst(root.left);
    deque.addLast(root.right);

    while (!deque.isEmpty()) {
        TreeNode leftNode = deque.removeFirst();
        TreeNode rightNode = deque.removeLast();

        if (leftNode == null && rightNode == null) {
            continue;
        }

        if (leftNode == null || rightNode == null) {
            return false;
        }

        if (leftNode.val != rightNode.val) {
            return false;
        }

        deque.addFirst(leftNode.right);
        deque.addFirst(leftNode.left);
        deque.addLast(rightNode.left);
        deque.addLast(rightNode.right);
    }

    return true;
}
 
Example 16
Source File: AsyncWorker.java    From logback-awslogs-appender with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Collection<InputLogEvent> drainBatchFromQueue() {
    Deque<InputLogEvent> batch = new ArrayDeque<InputLogEvent>(maxBatchLogEvents);
    queue.drainTo(batch, MAX_BATCH_LOG_EVENTS);
    int batchSize = batchSize(batch);
    while (batchSize > MAX_BATCH_SIZE) {
        InputLogEvent removed = batch.removeLast();
        batchSize -= eventSize(removed);
        if (!queue.offer(removed)) {
            getAwsLogsAppender().addWarn("Failed requeing message from too big batch");
        }
    }
    return batch;
}
 
Example 17
Source File: PlainSaslServer.java    From incubator-retired-blur with Apache License 2.0 4 votes vote down vote up
public byte[] evaluateResponse(byte[] response) throws SaslException {
  try {
    // parse the response
    // message   = [authzid] UTF8NUL authcid UTF8NUL passwd'

    Deque<String> tokenList = new ArrayDeque<String>();
    StringBuilder messageToken = new StringBuilder();
    for (byte b : response) {
      if (b == 0) {
        tokenList.addLast(messageToken.toString());
        messageToken = new StringBuilder();
      } else {
        messageToken.append((char)b);
      }
    }
    tokenList.addLast(messageToken.toString());

    // validate response
    if ((tokenList.size() < 2) || (tokenList.size() > 3)) {
      throw new SaslException("Invalid message format");
    }
    _passwd = tokenList.removeLast();
    _user = tokenList.removeLast();
    // optional authzid
    if (!tokenList.isEmpty()) {
      _authzId = tokenList.removeLast();
    } else {
      _authzId = _user;
    }
    if (_user == null || _user.isEmpty()) {
      throw new SaslException("No user name provide");
    }
    if (_passwd == null || _passwd.isEmpty()) {
      throw new SaslException("No password name provide");
    }

    NameCallback nameCallback = new NameCallback("User");
    nameCallback.setName(_user);
    PasswordCallback pcCallback = new PasswordCallback("Password", false);
    pcCallback.setPassword(_passwd.toCharArray());
    AuthorizeCallback acCallback = new AuthorizeCallback(_user, _authzId);

    Callback[] cbList = new Callback[] {nameCallback, pcCallback, acCallback};
    _handler.handle(cbList);
    if (!acCallback.isAuthorized()) {
      throw new SaslException("Authentication failed");
    }
  } catch (IllegalStateException eL) {
    throw new SaslException("Invalid message format", eL);
  } catch (IOException eI) {
    throw new SaslException("Error validating the login", eI);
  } catch (UnsupportedCallbackException eU) {
    throw new SaslException("Error validating the login", eU);
  }
  return null;
}
 
Example 18
Source File: InverseDepsAnalyzer.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns all paths reachable from the given targets.
 */
private Set<Deque<Archive>> findPaths(Graph<Archive> graph, Archive target) {

    // path is in reversed order
    Deque<Archive> path = new LinkedList<>();
    path.push(target);

    Set<Edge<Archive>> visited = new HashSet<>();

    Deque<Edge<Archive>> deque = new LinkedList<>();
    deque.addAll(graph.edgesFrom(target));
    if (deque.isEmpty()) {
        return makePaths(path).collect(Collectors.toSet());
    }

    Set<Deque<Archive>> allPaths = new HashSet<>();
    while (!deque.isEmpty()) {
        Edge<Archive> edge = deque.pop();

        if (visited.contains(edge))
            continue;

        Archive node = edge.v;
        path.addLast(node);
        visited.add(edge);

        Set<Edge<Archive>> unvisitedDeps = graph.edgesFrom(node)
                .stream()
                .filter(e -> !visited.contains(e))
                .collect(Collectors.toSet());

        trace("visiting %s %s (%s)%n", edge, path, unvisitedDeps);
        if (unvisitedDeps.isEmpty()) {
            makePaths(path).forEach(allPaths::add);
            path.removeLast();
        }

        // push unvisited adjacent edges
        unvisitedDeps.stream().forEach(deque::push);


        // when the adjacent edges of a node are visited, pop it from the path
        while (!path.isEmpty()) {
            if (visited.containsAll(graph.edgesFrom(path.peekLast())))
                path.removeLast();
            else
                break;
        }
    }

   return allPaths;
}
 
Example 19
Source File: LbKeogh.java    From tsml with GNU General Public License v3.0 4 votes vote down vote up
public static void fillULStreaming(final double[] y, final int r, final double[] U, final double[] L) {
    Deque<Integer> u = new ArrayDeque<>();
    Deque<Integer> l = new ArrayDeque<>();
    u.addLast(0);
    l.addLast(0);
    final int width = 1 + 2 * r;
    int i;
    for (i = 1; i < y.length; ++i) {
        if (i >= r + 1) {
            U[i - r - 1] = y[u.getFirst()];
            L[i - r - 1] = y[l.getFirst()];
        }
        if (y[i] > y[i - 1]) {
            u.removeLast();
            while (u.size() > 0) {
                if (y[i] <= y[u.getLast()]) break;
                u.removeLast();
            }
        } else {
            l.removeLast();
            while (l.size() > 0) {
                if (y[i] >= y[l.getLast()]) break;
                l.removeLast();
            }
        }
        u.addLast(i);
        l.addLast(i);
        if (i == width + u.getFirst()) {
            u.removeFirst();
        } else if (i == width + l.getFirst()) {
            l.removeFirst();
        }
    }

    for (i = y.length; i <= y.length + r; ++i) {
        final int index = Math.max(i - r - 1, 0);
        U[index] = y[u.getFirst()];
        L[index] = y[l.getFirst()];
        if (i - u.getFirst() >= width) {
            u.removeFirst();
        }
        if (i - l.getFirst() >= width) {
            l.removeFirst();
        }
    }
}
 
Example 20
Source File: AliasMethod.java    From DevUtils with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs a new AliasMethod to sample from a discrete distribution and
 * hand back outcomes based on the probability distribution.
 * <p>
 * Given as input a list of probabilities corresponding to outcomes 0, 1,
 * ..., n - 1, along with the random number generator that should be used
 * as the underlying generator, this constructor creates the probability
 * and alias tables needed to efficiently sample from this distribution.
 * @param probabilities The list of probabilities.
 * @param random        The random number generator
 */
public AliasMethod(List<Double> probabilities, Random random) {
    /* Begin by doing basic structural checks on the inputs. */
    if (probabilities == null || random == null)
        throw new NullPointerException();
    if (probabilities.size() == 0)
        throw new IllegalArgumentException("Probability vector must be nonempty.");

    /* Allocate space for the probability and alias tables. */
    probability = new double[probabilities.size()];
    alias = new int[probabilities.size()];

    /* Store the underlying generator. */
    this.random = random;

    /* Compute the average probability and cache it for later use. */
    final double average = 1.0 / probabilities.size();

    /* Make a copy of the probabilities list, since we will be making
     * changes to it.
     */
    probabilities = new ArrayList<Double>(probabilities);

    /* Create two stacks to act as worklists as we populate the tables. */
    Deque<Integer> small = new ArrayDeque<>();
    Deque<Integer> large = new ArrayDeque<>();

    /* Populate the stacks with the input probabilities. */
    for (int i = 0; i < probabilities.size(); ++i) {
        /* If the probability is below the average probability, then we add
         * it to the small list; otherwise we add it to the large list.
         */
        if (probabilities.get(i) >= average)
            large.add(i);
        else
            small.add(i);
    }

    /* As a note: in the mathematical specification of the algorithm, we
     * will always exhaust the small list before the big list.  However,
     * due to floating point inaccuracies, this is not necessarily true.
     * Consequently, this inner loop (which tries to pair small and large
     * elements) will have to check that both lists aren't empty.
     */
    while (!small.isEmpty() && !large.isEmpty()) {
        /* Get the index of the small and the large probabilities. */
        int less = small.removeLast();
        int more = large.removeLast();

        /* These probabilities have not yet been scaled up to be such that
         * 1/n is given weight 1.0.  We do this here instead.
         */
        probability[less] = probabilities.get(less) * probabilities.size();
        alias[less] = more;

        /* Decrease the probability of the larger one by the appropriate
         * amount.
         */
        probabilities.set(more,
                (probabilities.get(more) + probabilities.get(less)) - average);

        /* If the new probability is less than the average, add it into the
         * small list; otherwise add it to the large list.
         */
        if (probabilities.get(more) >= 1.0 / probabilities.size())
            large.add(more);
        else
            small.add(more);
    }

    /* At this point, everything is in one list, which means that the
     * remaining probabilities should all be 1/n.  Based on this, set them
     * appropriately.  Due to numerical issues, we can't be sure which
     * stack will hold the entries, so we empty both.
     */
    while (!small.isEmpty())
        probability[small.removeLast()] = 1.0;
    while (!large.isEmpty())
        probability[large.removeLast()] = 1.0;
}