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

The following examples show how to use java.util.Deque#peekLast() . 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: Solution2.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;
    if (len < 2) {
        return new int[len];
    }

    int[] res = new int[len];
    // 栈里存下标;对应的值的特点,单调不增;出栈的时候,记录 res
    Deque<Integer> stack = new ArrayDeque<>();
    for (int i = 0; i < len; i++) {
        while (!stack.isEmpty() && T[stack.peekLast()] < T[i]) {
            int index = stack.removeLast();
            res[index] = i - index;
        }
        stack.addLast(i);
    }

    // 最后在栈里的元素保持单调不增,因此下面这三行代码可以省略
    while (!stack.isEmpty()) {
        res[stack.pop()] = 0;
    }
    return res;
}
 
Example 2
Source File: Solution11.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 < 1) {
        return new int[0];
    }
    int[] res = new int[len - k + 1];
    Deque<Integer> deque = new ArrayDeque<>(k + 1);
    for (int i = 0; i < len; i++) {
        // 考虑删除队首元素
        if (i >= k && !deque.isEmpty() && deque.peekFirst() == i - k) {
            deque.pollFirst();
        }
        while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) {
            deque.pollLast();
        }
        deque.addLast(i);
        // 形成一个单调不减的队列,队首是滑动窗口的最大值
        // 记录结果集
        if (i >= k - 1) {
            res[i - k + 1] = nums[deque.peekFirst()];
        }
    }
    return res;
}
 
Example 3
Source File: FlatTraceGenerator.java    From besu with Apache License 2.0 6 votes vote down vote up
private static FlatTrace.Context handleHalt(
    final Deque<FlatTrace.Context> tracesContexts,
    final FlatTrace.Context currentContext,
    final TraceFrame traceFrame) {
  final FlatTrace.Builder traceFrameBuilder = currentContext.getBuilder();
  traceFrameBuilder.error(
      traceFrame.getExceptionalHaltReason().map(ExceptionalHaltReason::getDescription));
  final Action.Builder actionBuilder = traceFrameBuilder.getActionBuilder();
  actionBuilder.value(Quantity.create(traceFrame.getValue()));
  tracesContexts.removeLast();
  final FlatTrace.Context nextContext = tracesContexts.peekLast();
  if (nextContext != null) {
    nextContext.getBuilder().incSubTraces();
  }
  return nextContext;
}
 
Example 4
Source File: Solution2.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
    int len1 = nums1.length;
    int len2 = nums2.length;

    Deque<Integer> stack = new ArrayDeque<>();
    Map<Integer, Integer> map = new HashMap<>();
    // 对 nums2 先预处理
    for (int i = 0; i < len2; i++) {
        while (!stack.isEmpty() && stack.peekLast() < nums2[i]) {
            map.put(stack.removeLast(), nums2[i]);
        }
        stack.addLast(nums2[i]);
    }

    // 遍历 nums1 得到结果集
    int[] res = new int[len1];
    for (int i = 0; i < len1; i++) {
        res[i] = map.getOrDefault(nums1[i], -1);
    }
    return res;
}
 
Example 5
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 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: LocalLocation.java    From twill with Apache License 2.0 6 votes vote down vote up
@Override
public boolean delete(boolean recursive) throws IOException {
  if (!recursive) {
    return delete();
  }

  Deque<File> stack = new LinkedList<File>();
  stack.add(file);
  while (!stack.isEmpty()) {
    File f = stack.peekLast();
    File[] files = f.listFiles();

    if (files != null && files.length != 0) {
      Collections.addAll(stack, files);
    } else {
      if (!f.delete()) {
        return false;
      }
      stack.pollLast();
    }
  }
  return true;
}
 
Example 8
Source File: AmbientBrightnessStatsTracker.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private AmbientBrightnessDayStats getOrCreateDayStats(
        Deque<AmbientBrightnessDayStats> userStats, LocalDate localDate) {
    AmbientBrightnessDayStats lastBrightnessStats = userStats.peekLast();
    if (lastBrightnessStats != null && lastBrightnessStats.getLocalDate().equals(
            localDate)) {
        return lastBrightnessStats;
    } else {
        AmbientBrightnessDayStats dayStats = new AmbientBrightnessDayStats(localDate,
                BUCKET_BOUNDARIES_FOR_NEW_STATS);
        if (userStats.size() == MAX_DAYS_TO_TRACK) {
            userStats.poll();
        }
        userStats.offer(dayStats);
        return dayStats;
    }
}
 
Example 9
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 10
Source File: Solution2.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
public ListNode getIntersectionNode(ListNode pHead1, ListNode pHead2) {
    if (pHead1 == null || pHead2 == null) {
        return null;
    }
    Deque<ListNode> stack1 = new ArrayDeque<>();
    Deque<ListNode> stack2 = new ArrayDeque<>();
    ListNode curNode = pHead1;
    while (curNode != null) {
        stack1.addLast(curNode);
        curNode = curNode.next;
    }
    curNode = pHead2;
    while (curNode != null) {
        stack2.addLast(curNode);
        curNode = curNode.next;
    }

    ListNode res = null;
    // 因为是公共结点,所以他们的地址一定一样,可以用 ==
    while (!stack1.isEmpty() && !stack2.isEmpty() && stack1.peekLast() == stack2.peekLast()) {
        stack1.removeLast();
        res = stack2.removeLast();
    }
    return res;
}
 
Example 11
Source File: JimfsPath.java    From jimfs with Apache License 2.0 6 votes vote down vote up
@Override
public JimfsPath normalize() {
  if (isNormal()) {
    return this;
  }

  Deque<Name> newNames = new ArrayDeque<>();
  for (Name name : names) {
    if (name.equals(Name.PARENT)) {
      Name lastName = newNames.peekLast();
      if (lastName != null && !lastName.equals(Name.PARENT)) {
        newNames.removeLast();
      } else if (!isAbsolute()) {
        // if there's a root and we have an extra ".." that would go up above the root, ignore it
        newNames.add(name);
      }
    } else if (!name.equals(Name.SELF)) {
      newNames.add(name);
    }
  }

  return Iterables.elementsEqual(newNames, names) ? this : pathService.createPath(root, newNames);
}
 
Example 12
Source File: Solution.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
public String removeKdigits(String num, int k) {
    int len = num.length();
    if (len == k) {
        return "0";
    }

    int remaining = len - k;
    char[] charArray = num.toCharArray();
    Deque<Character> stack = new ArrayDeque<>();
    for (char c : charArray) {
        while (k > 0 && !stack.isEmpty() && stack.peekLast() > c) {
            stack.removeLast();
            k--;
        }
        stack.addLast(c);
    }

    // System.out.println(stack);
    // 只取前面剩下的部分,针对 String num = "112"; int k = 1; 这种用例
    while (stack.size() > remaining) {
        stack.pollLast();
    }

    while (!stack.isEmpty() && stack.peekFirst() == '0') {
        stack.removeFirst();
    }

    if (stack.isEmpty()) {
        return "0";
    }
    return toString(stack);
}
 
Example 13
Source File: Solution2.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
public int largestRectangleArea(int[] heights) {
    int len = heights.length;
    if (len == 0) {
        return 0;
    }
    if (len == 1) {
        return heights[0];
    }

    int area = 0;
    int[] newHeights = new int[len + 2];
    for (int i = 0; i < len; i++) {
        newHeights[i + 1] = heights[i];
    }
    len += 2;
    heights = newHeights;

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

    for (int i = 1; i < len; i++) {
        while (heights[stack.peekLast()] > heights[i]) {
            int height = heights[stack.removeLast()];
            int width  = i - stack.peekLast() - 1;
            area = Math.max(area, width * height);
        }
        stack.addLast(i);
    }
    return area;
}
 
Example 14
Source File: _059_Max_Value_In_Slide_Window.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();
            }
        }

        // 同一个窗口中的元素如果小于新元素,则被删除
        // 由于前面的元素总是大于后面的元素,所以从后面开始删除
        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 15
Source File: InventoryGui.java    From InventoryGui with MIT License 5 votes vote down vote up
/**
 * Add a new history entry to the end of the history
 * @param player    The player to add the history entry for
 * @param gui       The GUI to add to the history
 */
public static void addHistory(HumanEntity player, InventoryGui gui) {
    GUI_HISTORY.putIfAbsent(player.getUniqueId(), new ArrayDeque<>());
    Deque<InventoryGui> history = getHistory(player);
    if (history.peekLast() != gui) {
        history.add(gui);
    }
}
 
Example 16
Source File: FormData.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
public FormValue getLast(String name) {
    final Deque<FormValue> deque = values.get(name);
    return deque == null ? null : deque.peekLast();
}
 
Example 17
Source File: Solution3.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 4 votes vote down vote up
public String removeDuplicateLetters(String s) {
    int len = s.length();
    // 特判
    if (len < 2) {
        return s;
    }

    char[] charArray = s.toCharArray();

    // 记录每个字符出现的最后一个位置
    int[] lastAppearIndex = new int[26];
    for (int i = 0; i < len; i++) {
        lastAppearIndex[charArray[i] - 'a'] = i;
    }

    // 记录是否在已经得到的字符串中
    boolean[] set = new boolean[26];

    Deque<Character> stack = new ArrayDeque<>();
    // 此时 `a` 作为哨兵,这个 `a` 永远不会被弹出
    // 如此一来,在遍历的时候,就不用判断栈是否为空了
    stack.addLast('a');

    for (int i = 0; i < len; i++) {
        char currentChar = charArray[i];
        if (set[currentChar - 'a']) {
            continue;
        }

        while (stack.peekLast() > currentChar && lastAppearIndex[stack.peekLast() - 'a'] >= i) {
            char top = stack.removeLast();
            set[top - 'a'] = false;
        }

        stack.addLast(currentChar);
        set[currentChar - 'a'] = true;
    }

    int size = stack.size();
    StringBuilder stringBuilder = new StringBuilder();
    // 注意:这里只弹栈 size - 1 次
    for (int i = 0; i < size - 1; i++) {
        stringBuilder.insert(0, stack.removeLast());
    }
    return stringBuilder.toString();
}
 
Example 18
Source File: OfdpaGroupHandlerUtility.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Get indices to remove comparing next group with next objective.
 *
 * @param allActiveKeys the representation of the group
 * @param nextObjective the next objective to verify
 * @param groupService groups service for querying group information
 * @param deviceId the device id for the device that contains the group
 * @return a list of indexes in the allActiveKeys to remove.
 */
public static List<Integer> indicesToRemoveFromNextGroup(List<Deque<GroupKey>> allActiveKeys,
                                                   NextObjective nextObjective,
                                                   GroupService groupService,
                                                   DeviceId deviceId) {
    List<Integer> indicesToRemove = Lists.newArrayList();
    int index = 0;
    // Iterate over the chain in the next data
    for (Deque<GroupKey> keyChain : allActiveKeys) {
        // Valid chain should have at least two elements
        if (keyChain.size() >= 2) {
            // Get last group (l2if) and retrieve port number
            GroupKey ifaceGroupKey = keyChain.peekLast();
            Group ifaceGroup = groupService.getGroup(deviceId, ifaceGroupKey);
            if (ifaceGroup != null && !ifaceGroup.buckets().buckets().isEmpty()) {
                PortNumber portNumber = readOutPortFromTreatment(
                        ifaceGroup.buckets().buckets().iterator().next().treatment());
                // If there is not a port number continue
                if (portNumber != null) {
                    // check for label in the 2nd group of this chain
                    GroupKey secondKey = (GroupKey) keyChain.toArray()[1];
                    Group secondGroup = groupService.getGroup(deviceId, secondKey);
                    // If there is not a second group or there are no buckets continue
                    if (secondGroup != null && !secondGroup.buckets().buckets().isEmpty()) {
                        // Get label or -1
                        int label = readLabelFromTreatment(
                                secondGroup.buckets().buckets()
                                        .iterator().next().treatment());
                        // Iterate over the next treatments looking for the port and the label
                        boolean matches = false;
                        for (TrafficTreatment t : nextObjective.next()) {
                            PortNumber tPort = readOutPortFromTreatment(t);
                            int tLabel = readLabelFromTreatment(t);
                            if (tPort != null && tPort.equals(portNumber) && tLabel == label) {
                                // We found it, exit
                                matches = true;
                                break;
                            }
                        }
                        // Not found, we have to remove it
                        if (!matches) {
                            indicesToRemove.add(index);
                        }
                    }
                }
            }
        }
        index++;
    }
    return indicesToRemove;
}
 
Example 19
Source File: StorageManager.java    From packagedrone with Eclipse Public License 1.0 4 votes vote down vote up
protected static State getCurrent ()
{
    final Deque<State> stack = lockStates.get ();
    return stack.peekLast ();
}
 
Example 20
Source File: FormData.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public FormValue getLast(String name) {
    final Deque<FormValue> deque = values.get(name);
    return deque == null ? null : deque.peekLast();
}