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

The following examples show how to use java.util.ArrayDeque#peekLast() . These examples are extracted from open source projects. 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
/**
 * 滑动窗口应当是队列,但为了得到滑动窗口的最大值,队列序可以从两端删除元素,因此使用双端队列。 对新来的元素k,将其与双端队列中的元素相比较
 * 1)前面比k小的,直接移出队列(因为不再可能成为后面滑动窗口的最大值了!), 2)前面比k大的X,比较两者下标,判断X是否已不在窗口之内,不在了,直接移出队列
 * 队列的第一个元素是滑动窗口中的最大值
 */
public ArrayList<Integer> maxInWindows(int[] num, int size) {
    ArrayList<Integer> list = new ArrayList<>();
    if (size == 0) return list;
    int start = 0;
    // 用来保存可能是滑动窗口最大值的数字的下标
    ArrayDeque<Integer> index = new ArrayDeque<>();
    for (int i = 0; i < num.length; i++) {
        start = i - size + 1;
        if (index.isEmpty()) index.add(i);
        // 如果队列的头部元素已经从滑动窗口里滑出,滑出的数字需要从队列的头部删除
        else if (start > index.peekFirst()) index.pollFirst();
        // 数组:{2,3,4,2,6,2,5,1}
        // 如果已有数字小于待存入的数据, 这些数字已经不可能是滑动窗口的最大值
        // 因此它们将会依次地从队尾删除
        while ((!index.isEmpty()) && num[index.peekLast()] <= num[i]) index.pollLast();
        index.add(i);
        if (start >= 0) list.add(num[index.peekFirst()]);
    }
    return list;
}
 
Example 2
public int[] maxSlidingWindow(int[] nums, int k) {
    int len = nums.length;
    // 特判
    if (len == 0) {
        return new int[]{};
    }
    // 结果集
    List<Integer> res = new ArrayList<>();
    // 滑动窗口,注意:保存的是索引值
    ArrayDeque<Integer> deque = new ArrayDeque<>(k);

    for (int i = 0; i < len; i++) {
        // 当元素从左边界滑出的时候,如果它恰恰好是滑动窗口的最大值
        // 那么将它弹出
        if (i >= k && i - k == deque.getFirst()) {
            deque.pollFirst();
        }

        // 如果滑动窗口非空,新进来的数比队列里已经存在的数还要大
        // 则说明已经存在数一定不会是滑动窗口的最大值(它们毫无出头之日)
        // 将它们弹出
        while (!deque.isEmpty() && nums[deque.peekLast()] <= nums[i]) {
            deque.pollLast();
        }
        deque.add(i);
        // 队首一定是滑动窗口的最大值的索引
        if (i >= k - 1) {
            res.add(nums[deque.peekFirst()]);
        }
    }

    int size = res.size();
    int[] result = new int[size];

    for (int i = 0; i < size; i++) {
        result[i] = res.get(i);
    }
    return result;
}
 
Example 3
Source Project: Android-Cheat-sheet   File: Dequeue.java    License: 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 4
/**
 * 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 5
/**
 * Get the normalized path for the given file path.
 * Any parent directories (..) will be resolved.
 * @param file file path
 * @return 
 */
public static String getNormalizedPath(String file) {
    Matcher m = schemedPathPattern.matcher(file);
    if(!m.find()) {
        return Directory.ROOT_DIRECTORY;
    }
    String scheme = m.group(1);
    String path = m.group(2);
    if(scheme == null) {
        scheme = "";
    }
    String[] st = path.split("(\\\\|/)+");
    ArrayDeque<String> segmentList = new ArrayDeque<String>();
    for(String segment : st) {
        if("..".equals(segment)) {
            segmentList.pollFirst();
            continue;
        }
        segmentList.offerFirst(segment);
    }
    if(segmentList.isEmpty() && scheme.isEmpty()) {
        return Directory.ROOT_DIRECTORY;
    }
    StringBuilder sb = new StringBuilder();
    sb.append(scheme);
    while(!segmentList.isEmpty()) {
        sb.append(segmentList.pollLast());
        if(segmentList.peekLast() != null) {
            sb.append('/');
        }
    }
    return sb.length() == 0 ? Directory.ROOT_DIRECTORY : sb.toString();
}
 
Example 6
Source Project: Any-Angle-Pathfinding   File: KeyToggler.java    License: 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 7
Source Project: grpc-java   File: EdsLoadBalancerTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void edsResourceUpdate_endpointAssignmentChange() {
  final ArrayDeque<LocalityStore> localityStores = new ArrayDeque<>();
  localityStoreFactory = new LocalityStoreFactory() {
    @Override
    LocalityStore newLocalityStore(
        InternalLogId logId,
        Helper helper,
        LoadBalancerRegistry lbRegistry,
        LoadStatsStore loadStatsStore) {
      // Note that this test approach can not verify anything about how localityStore will use the
      // helper in the arguments to delegate updates from localityStore to the EDS balancer, and
      // can not verify anything about how loadStatsStore updates localities and drop information.
      // To cover the gap, some non-exhaustive tests like
      // handleAllDropUpdates_pickersAreDropped() and
      // handleLocalityAssignmentUpdates_pickersUpdatedFromChildBalancer()are added to verify some
      // very basic behaviors.
      LocalityStore localityStore = mock(LocalityStore.class);
      localityStores.add(localityStore);
      return localityStore;
    }
  };
  edsLb =
      new EdsLoadBalancer(helper, lbRegistry, localityStoreFactory, bootstrapper, channelFactory);

  deliverResolvedAddresses("edsServiceName1", null, fakeEndpointPickingPolicy);
  assertThat(localityStores).hasSize(1);
  LocalityStore localityStore = localityStores.peekLast();

  ClusterLoadAssignment clusterLoadAssignment = buildClusterLoadAssignment(
      "edsServiceName1",
      ImmutableList.of(
          buildLocalityLbEndpoints("region1", "zone1", "subzone1",
              ImmutableList.of(
                  buildLbEndpoint("192.168.0.1", 8080, HEALTHY, 2)),
              1, 0)),
      ImmutableList.of(
          buildDropOverload("cat_1", 3),
          buildDropOverload("cat_2", 456)));
  deliverClusterLoadAssignments(clusterLoadAssignment);
  EndpointUpdate endpointUpdate = getEndpointUpdateFromClusterAssignment(clusterLoadAssignment);
  verify(localityStore).updateDropPercentage(endpointUpdate.getDropPolicies());
  verify(localityStore).updateLocalityStore(endpointUpdate.getLocalityLbEndpointsMap());

  clusterLoadAssignment = buildClusterLoadAssignment(
      "edsServiceName1",
      ImmutableList.of(
          buildLocalityLbEndpoints("region1", "zone1", "subzone1",
              ImmutableList.of(
                  buildLbEndpoint("192.168.0.1", 8080, HEALTHY, 2),
                  buildLbEndpoint("192.168.0.1", 8088, HEALTHY, 2)),
              1, 0)),
      ImmutableList.of(
          buildDropOverload("cat_1", 3),
          buildDropOverload("cat_3", 4)));
  deliverClusterLoadAssignments(clusterLoadAssignment);

  endpointUpdate = getEndpointUpdateFromClusterAssignment(clusterLoadAssignment);
  verify(localityStore).updateDropPercentage(endpointUpdate.getDropPolicies());
  verify(localityStore).updateLocalityStore(endpointUpdate.getLocalityLbEndpointsMap());

  // Change cluster name.
  deliverResolvedAddresses("edsServiceName2", null, fakeEndpointPickingPolicy);
  assertThat(localityStores).hasSize(2);
  localityStore = localityStores.peekLast();

  clusterLoadAssignment = buildClusterLoadAssignment(
      "edsServiceName2",
      ImmutableList.of(
          buildLocalityLbEndpoints("region2", "zone2", "subzone2",
              ImmutableList.of(
                  buildLbEndpoint("192.168.0.2", 8080, HEALTHY, 2),
                  buildLbEndpoint("192.168.0.2", 8088, HEALTHY, 2)),
              1, 0)),
      ImmutableList.of(
          buildDropOverload("cat_1", 3),
          buildDropOverload("cat_3", 4)));
  deliverClusterLoadAssignments(clusterLoadAssignment);
  endpointUpdate = getEndpointUpdateFromClusterAssignment(clusterLoadAssignment);
  verify(localityStore).updateDropPercentage(endpointUpdate.getDropPolicies());
  verify(localityStore).updateLocalityStore(endpointUpdate.getLocalityLbEndpointsMap());
}