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

The following examples show how to use java.util.Deque#peekFirst() . 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: Solution.java    From daily-coding-problems with Apache License 2.0 6 votes vote down vote up
int[] getMaximumInSubArray(int[] array, int window) {
    List<Integer> result = new ArrayList<>();
    if (array == null || array.length == 0) {
        return new int[0];
    }
    if (window > array.length) {
        throw new IllegalArgumentException("window should be less than the array length");
    }

    Deque<Integer> deque = new ArrayDeque<>();
    for (int index = 0; index < array.length; index++) {
        if (!deque.isEmpty() && deque.peekFirst() == index - window) {
            deque.removeFirst();
        }
        while (!deque.isEmpty() && array[index] > array[deque.peekLast()]) {
            deque.removeLast();
        }

        deque.addLast(index);
        if (index >= window - 1) {
            result.add(array[deque.peekFirst()]);
        }
    }
    return result.stream().mapToInt(x -> x).toArray();
}
 
Example 2
Source File: Helper.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Returns the value of the "queries" request parameter, which is an integer
 * bound between 1 and 500 with a default value of 1.
 *
 * @param exchange the current HTTP exchange
 * @return the value of the "queries" request parameter
 */
public static int getQueries(HttpServerExchange exchange) {
    Deque<String> values = exchange.getQueryParameters().get("queries");
    if (values == null) {
        return 1;
    }
    String textValue = values.peekFirst();
    if (textValue == null) {
        return 1;
    }
    try {
        int parsedValue = Integer.parseInt(textValue);
        return Math.min(500, Math.max(1, parsedValue));
    } catch (NumberFormatException e) {
        return 1;
    }
}
 
Example 3
Source File: LinkedDequeTest.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "warmedDeque")
public void removeLastOccurrence_whenFound(Deque<SimpleLinkedValue> deque) {
  SimpleLinkedValue first = deque.peekFirst();
  assertThat(deque.removeLastOccurrence(first), is(true));
  assertThat(deque, hasSize((int) capacity() - 1));
  assertThat(deque.contains(first), is(false));
}
 
Example 4
Source File: TreeTraversalInSpiralOrder.java    From interview with Apache License 2.0 5 votes vote down vote up
/**
 * One deque with delimiter to print tree in spiral order
 */
public void spiralWithOneDequeDelimiter(Node root)
{
    if(root == null){
        return;
    }
    Deque<Node> q = new LinkedList<>();
    q.offer(null);
    q.offerFirst(root);
    //if only delimiter(in this case null) is left in queue then break
    while(q.size() > 1){
        root = q.peekFirst();
        while(root != null){
            root = q.pollFirst();
            System.out.print(root.data + " ");
            if(root.left != null){
                q.offerLast(root.left);
            }
            if(root.right != null){
                q.offerLast(root.right);
            }
            root = q.peekFirst();
        }
        root = q.peekLast();
        while(root != null){
            System.out.print(root.data + " ");
            root = q.pollLast();
            if(root.right != null){
                q.offerFirst(root.right);
            }
            if(root.left != null){
                q.offerFirst(root.left);
            }
            root = q.peekLast();
        }
    }
}
 
Example 5
Source File: LinkedDequeTest.java    From multiway-pool with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "warmedDeque")
public void removeFirstOccurrence_whenFound(Deque<SimpleLinkedValue> deque) {
  SimpleLinkedValue first = deque.peekFirst();
  assertThat(deque.removeFirstOccurrence(first), is(true));
  assertThat(deque, hasSize((int) capacity() - 1));
  assertThat(deque.contains(first), is(false));
}
 
Example 6
Source File: LinkedDequeTest.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "warmedDeque")
public void removeElement_whenFound(Deque<SimpleLinkedValue> deque) {
  SimpleLinkedValue first = deque.peekFirst();
  assertThat(deque.remove(first), is(true));
  assertThat(deque, hasSize((int) capacity() - 1));
  assertThat(deque.contains(first), is(false));
}
 
Example 7
Source File: ASTReference.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * This method helps to implement the "render literal if null" functionality.
 *
 * VelocimacroProxy saves references to macro arguments (AST nodes) so that if we have a macro
 * #foobar($a $b) then there is key "$a.literal" which points to the literal presentation of the
 * argument provided to variable $a. If the value of $a is null, we render the string that was
 * provided as the argument.
 *
 * @param context
 * @return
 */
private String getNullString(InternalContextAdapter context)
{
    String ret = nullString;

    if (lookupAlternateLiteral)
    {
        Deque<String> alternateLiteralsStack = (Deque<String>)context.get(alternateNullStringKey);
        if (alternateLiteralsStack != null && alternateLiteralsStack.size() > 0)
        {
            ret = alternateLiteralsStack.peekFirst();
        }
    }
    return ret;
}
 
Example 8
Source File: Test65.java    From algorithm-primer with MIT License 5 votes vote down vote up
public ArrayList<Integer> maxInWindows(int[] num, int size) {
    ArrayList<Integer> result = new ArrayList<>();
    if (num == null || num.length == 0 || size < 1) return result;

    Deque<Integer> deque = new LinkedList<>();
    for (int i = 0; i < num.length; i ++){
        // 保证添加新的元素之前,窗口中首尾元素下标之差最大是size
        if (i > 0 && !deque.isEmpty()){
            int firstIdx = deque.peekFirst();
            int diff = i - firstIdx;
            if (diff == size)
                deque.pollFirst();
        }
        /*
        if (!deque.isEmpty() && num[i] > deque.peekFirst()){
            deque.clear();
        }else{
            while(!deque.isEmpty() && num[i] >= deque.peekLast())
                deque.pollLast();
        }
        */

        // 同一个窗口中的元素如果小于新元素,则被删除
        // 由于前面的元素总是大于后面的元素,所以从后面开始删除
        while(!deque.isEmpty() && num[i] >= num[deque.peekLast()])
            deque.pollLast();

        // 新元素总是会被添加到双端队列的末尾
        deque.offerLast(i);

        // 双端队列的队头存放的是一个窗口的最大值
        if (i >= size-1)
            result.add(num[deque.peekFirst()]);
    }
    return result;
}
 
Example 9
Source File: LinkedDequeTest.java    From multiway-pool with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "warmedDeque")
public void removeElement_whenFound(Deque<SimpleLinkedValue> deque) {
  SimpleLinkedValue first = deque.peekFirst();
  assertThat(deque.remove(first), is(true));
  assertThat(deque, hasSize((int) capacity() - 1));
  assertThat(deque.contains(first), is(false));
}
 
Example 10
Source File: LinkedDequeTest.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "warmedDeque")
public void pollFirst_whenPopulated(Deque<SimpleLinkedValue> deque) {
  SimpleLinkedValue first = deque.peekFirst();
  assertThat(deque.pollFirst(), is(first));
  assertThat(deque, hasSize((int) capacity() - 1));
  assertThat(deque.contains(first), is(false));
}
 
Example 11
Source File: RemoveExtraBrackets.java    From interview with Apache License 2.0 5 votes vote down vote up
public int remove(char input[]){
    if(input == null){
        return 0;
    }
    Deque<Integer> dq = new LinkedList<Integer>();
    for(int i=0; i < input.length; i++){
        //skip non bracket characters
        if(input[i] != '(' && input[i] != ')'){
            continue;
        }
        
        //add opening brackets
        if(input[i] == '('){
            dq.addFirst(i);
        }
        else if(input[i] == ')'){
            //if top is opening bracket just remove from stack else add closing bracket
            if(!dq.isEmpty() && input[dq.peekFirst()] == '('){
                dq.pollFirst();
            }else{
                dq.addFirst(i);
            }
        }
    }
    int index = 0;
    //iterate through list again and don't add leftover
    //characters from stack in final result
    for(int i=0; i < input.length; i++){
        if(!dq.isEmpty() && i == dq.peekLast()) {
            dq.pollLast();
        }else {
            input[index++] = input[i];
        }
    }
    return index;
}
 
Example 12
Source File: MaximumOfSubarrayOfSizeK.java    From interview with Apache License 2.0 5 votes vote down vote up
public int[] maxSubArray(int input[], int k) {
    Deque<Integer> queue = new LinkedList<Integer>();
    int max[] = new int[input.length - k + 1];
    int maxVal = Integer.MIN_VALUE;
    //first find max of first k values and make it 0th element of max array
    for (int i = 0; i < k; i++) {
        if(maxVal < input[i]){
            maxVal = input[i];
        }
        if (queue.isEmpty()) {
            queue.offerLast(i);
        } else {
            while (!queue.isEmpty() && input[queue.peekLast()] <= input[i]) {
                queue.pollLast();
            }
            queue.offerLast(i);
        }
        
    }
    max[0] = maxVal;
    int index=1;
    //continue from k till end of the input array
    for (int i = k; i < input.length; i++) {
        //if index of peek is k distance from i then its no value to us.
        //throw it away
        if (i - k + 1 > queue.peekFirst()) {
            queue.pollFirst();
        }
        while (!queue.isEmpty() && input[queue.peekLast()] <= input[i]) {
            queue.pollLast();
        }
        queue.offerLast(i);
        //Only reason first element survived was because it was biggest element.
        //make it the max value for this k
        max[index] = input[queue.peekFirst()];
        index++;
    }
    return max;
}
 
Example 13
Source File: LinkedDequeTest.java    From multiway-pool with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "warmedDeque")
public void removeFirst_whenPopulated(Deque<SimpleLinkedValue> deque) {
  SimpleLinkedValue first = deque.peekFirst();
  assertThat(deque.removeFirst(), is(first));
  assertThat(deque, hasSize((int) capacity() - 1));
  assertThat(deque.contains(first), is(false));
}
 
Example 14
Source File: MCRFileSystemUtils.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
static MCRFile getMCRFile(MCRDirectory baseDir, MCRPath relativePath, boolean create, boolean createNew)
    throws IOException {
    MCRPath ifsPath = relativePath;
    if (relativePath.isAbsolute()) {
        if (baseDir.getOwnerID().equals(relativePath.getOwner())) {
            ifsPath = baseDir.toPath().relativize(relativePath);
        } else {
            throw new IOException(relativePath + " is absolute does not fit to " + baseDir.toPath());
        }
    }
    Deque<MCRFilesystemNode> created = new LinkedList<>();
    MCRFile file;
    try {
        file = (MCRFile) baseDir.getChildByPath(ifsPath.toString());
        if (file != null && createNew) {
            throw new FileAlreadyExistsException(baseDir.toPath().resolve(ifsPath).toString());
        }
        if (file == null & (create || createNew)) {
            Path normalized = ifsPath.normalize();
            MCRDirectory parent = baseDir;
            int nameCount = normalized.getNameCount();
            int directoryCount = nameCount - 1;
            int i = 0;
            while (i < directoryCount) {
                String curName = normalized.getName(i).toString();
                MCRDirectory curDir = (MCRDirectory) parent.getChild(curName);
                if (curDir == null) {
                    curDir = new MCRDirectory(curName, parent);
                    created.addFirst(curDir);
                }
                i++;
                parent = curDir;
            }
            String fileName = normalized.getFileName().toString();
            file = new MCRFile(fileName, parent);
            file.setContentFrom(new ByteArrayInputStream(new byte[0]), false);//false -> no event handler
            created.addFirst(file);
        }
    } catch (Exception e) {
        if (create || createNew) {
            LOGGER.error("Exception while getting MCRFile {}. Removing created filesystem nodes.", ifsPath);
            while (created.peekFirst() != null) {
                MCRFilesystemNode node = created.pollFirst();
                try {
                    node.delete();
                } catch (Exception de) {
                    LOGGER.fatal("Error while deleting file system node: {}", node.getName(), de);
                }
            }
        }
        throw e;
    }
    return file;
}
 
Example 15
Source File: PrintTwoBSTInSortedForm.java    From interview with Apache License 2.0 4 votes vote down vote up
public void print(Node root1, Node root2){
    Deque<Node> s1 = new LinkedList<Node>();
    Deque<Node> s2 = new LinkedList<Node>();
    
    while(true){
        if(root1 != null){
            s1.addFirst(root1);
            root1 = root1.left;
            continue;
        }
        if(root2 != null){
            s2.addFirst(root2);
            root2 = root2.left;
            continue;
        }
        if(!s1.isEmpty()){
            root1 = s1.peekFirst();
        }
        if(!s2.isEmpty()){
            root2 = s2.peekFirst();
        }
        if(root1 != null && root2 != null){
            if(root1.data <= root2.data){
                System.out.println(root1.data);
                root1 = s1.pollFirst();
                root1 = root1.right;
                root2 = null;
            }else{
                System.out.println(root2.data);
                root2 = s2.pollFirst();
                root2 = root2.right;
                root1 = null;
            }
        }
        else if(root1 != null){
            System.out.println(root1.data);
            root1 = s1.pollFirst();
            root1 = root1.right;
        
        }else if(root2 != null){
            System.out.println(root2.data);
            root2 = s2.pollFirst();
            root2 = root2.right;
        }
        if(root1 == null && root2 == null && s1.isEmpty() && s2.isEmpty()){
            break;
        }
    }
}
 
Example 16
Source File: FormData.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public FormValue getFirst(String name) {
    final Deque<FormValue> deque = values.get(name);
    return deque == null ? null : deque.peekFirst();
}
 
Example 17
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 4 votes vote down vote up
/**
 * Output a chain of dereferences where some prefix should be treated as a single syntactic unit,
 * either because it looks like a type name or because there is only a single method invocation in
 * the chain.
 *
 * @param items in the chain
 * @param needDot whether a leading dot is needed
 * @param prefixes the terminal indices of 'prefixes' of the expression that should be treated as
 *     a syntactic unit
 */
private void visitDotWithPrefix(
    List<ExpressionTree> items,
    boolean needDot,
    Collection<Integer> prefixes,
    FillMode prefixFillMode) {
  // Are there method invocations or field accesses after the prefix?
  boolean trailingDereferences = !prefixes.isEmpty() && getLast(prefixes) < items.size() - 1;

  builder.open(plusFour);
  for (int times = 0; times < prefixes.size(); times++) {
    builder.open(ZERO);
  }

  Deque<Integer> unconsumedPrefixes = new ArrayDeque<>(ImmutableSortedSet.copyOf(prefixes));
  BreakTag nameTag = genSym();
  for (int i = 0; i < items.size(); i++) {
    ExpressionTree e = items.get(i);
    if (needDot) {
      FillMode fillMode;
      if (!unconsumedPrefixes.isEmpty() && i <= unconsumedPrefixes.peekFirst()) {
        fillMode = prefixFillMode;
      } else {
        fillMode = FillMode.UNIFIED;
      }

      builder.breakOp(fillMode, "", ZERO, Optional.of(nameTag));
      token(".");
    }
    BreakTag tyargTag = genSym();
    dotExpressionUpToArgs(e, Optional.of(tyargTag));
    if (!unconsumedPrefixes.isEmpty() && i == unconsumedPrefixes.peekFirst()) {
      builder.close();
      unconsumedPrefixes.removeFirst();
    }

    Indent tyargIndent = Indent.If.make(tyargTag, plusFour, ZERO);
    Indent argsIndent = Indent.If.make(nameTag, plusFour, trailingDereferences ? plusFour : ZERO);
    dotExpressionArgsAndParen(e, tyargIndent, argsIndent);

    needDot = true;
  }

  builder.close();
}
 
Example 18
Source File: Solution496.java    From LeetCodeSolution with Apache License 2.0 4 votes vote down vote up
/**
 * 1.关于复杂度
 *     1.1 时间复杂度为O(m+n)
 *     1.2 空间负责度为O(n)
 * 2.我的解题思路
 *     2.1 因为我们需要得到当前元素在nums2的下一个最大元素,所以我们可以构成一个当前元素与在在nums2的下一个最大元素的一对一映射
 *     2.2 定义一个栈跟队列缓存结果
 *     2.3 循环遍历nums2
 *         2.3.1 如果当前栈不为空而且栈顶元素小于当前元素,将他们放入HashMap中
 *         2.3.2 将当前元素入栈
 *     2.4 遍历nums1获取HashMap对应的值
 * 3.提交记录
 *     3.1 力扣中耗时9ms,消耗37.8MB内存
 *     3.2 leetcode中耗时2ms,消耗37.1MB内存
 * 4.Q&A
 *
 * 1.About Complexity
 *     1.1 Time Complexity is O(m+n)(m is nums1.length,n is nums.length)
 *     1.2 Space Complexity is O(n)
 * 2.how I solve
 *     2.1 cache we need to mark next element on nums2,so it forms a one-to-one relationship with element on nums1 and bigger on element which bigger than element on nums2
 *     2.2 define a stack and hashMap to cache calculate result
 *     2.3 circulate nums2
 *         2.3.1 if stack is not empty,compare top element and current element,if current's is bigger than top's,put it to hashMap
 *         2.3.2 add current element to stack
 *     2.4 circulate nums1 and use current element to get value from HashMap
 * 3.About submit record
 *     3.1 9ms and 37.8MB memory in LeetCode China
 *     3.2 2ms and 37.1MB memory in LeetCode
 * 4.Q&A
 * @param nums1
 * @param nums2
 * @return
 */
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
    Deque<Integer> stack=new LinkedList<>();
    Map<Integer,Integer> map=new HashMap<>();
    for(int temp:nums2){
        while(stack.size()!=0&&stack.peekFirst()<temp){
            map.put(stack.removeFirst(),temp);
        }
        stack.addFirst(temp);
    }
    map.forEach((key,value)->{
        System.out.println(key+" "+value);
    });
    int[] res=new int[nums1.length];
    for(int i=0,length=res.length;i<length;i++){
        res[i]=map.getOrDefault(nums1[i],-1);
    }
    return res;
}
 
Example 19
Source File: AbstractFlinkClient.java    From alchemy with Apache License 2.0 4 votes vote down vote up
private Table registerSql(StreamTableEnvironment env, String sql, Map<String, TableSource> tableSources,
                          Map<String, SourceDescriptor> sideSources) throws Exception {
    if (sideSources.isEmpty()) {
        return env.sqlQuery(sql);
    }
    Deque<SqlNode> deque = SideParser.parse(sql);
    SqlNode last;
    SqlSelect modifyNode = null;
    SqlNode fullNode = deque.peekFirst();
    while ((last = deque.pollLast()) != null) {
        if (modifyNode != null) {
            SideParser.rewrite(last, modifyNode);
            modifyNode = null;
        }
        if (last.getKind() == SqlKind.SELECT) {
            SqlSelect sqlSelect = (SqlSelect) last;
            SqlNode selectFrom = sqlSelect.getFrom();
            if (SqlKind.JOIN != selectFrom.getKind()) {
                continue;
            }
            SqlJoin sqlJoin = (SqlJoin) selectFrom;
            Alias sideAlias = SideParser.getTableName(sqlJoin.getRight());
            Alias leftAlias = SideParser.getTableName(sqlJoin.getLeft());
            if (isSide(sideSources.keySet(), leftAlias.getTable())) {
                throw new UnsupportedOperationException("side table must be right table");
            }
            if (!isSide(sideSources.keySet(), sideAlias.getTable())) {
                continue;
            }
            DataStream<Row> dataStream = SideStream.buildStream(env, sqlSelect, leftAlias, sideAlias,
                sideSources.get(sideAlias.getTable()));
            Alias newTable = new Alias(leftAlias.getTable() + "_" + sideAlias.getTable(),
                leftAlias.getAlias() + "_" + sideAlias.getAlias());
            if (!env.isRegistered(newTable.getTable())) {
                env.registerDataStream(newTable.getTable(), dataStream);
            }
            SqlSelect newSelect
                = SideParser.newSelect(sqlSelect, newTable.getTable(), newTable.getAlias(), false, true);
            modifyNode = newSelect;
        }
    }
    if (modifyNode != null) {
        return env.sqlQuery(modifyNode.toString());
    } else {
        return env.sqlQuery(fullNode.toString());
    }

}
 
Example 20
Source File: FormData.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
public FormValue getFirst(String name) {
    final Deque<FormValue> deque = values.get(name);
    return deque == null ? null : deque.peekFirst();
}