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

The following examples show how to use java.util.Deque#getLast() . 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
/**
 * 双端队列
 *
 * @param nums
 * @param k
 * @return
 */
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];
    Deque<Integer> queue = new ArrayDeque<>();
    for (int i = 0; i < len; i++) {
        if (i >= k && queue.getFirst() == i - k) {
            queue.removeFirst();
        }
        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;
}
 
Example 2
Source File: BaragonStateWatcher.java    From Baragon with Apache License 2.0 6 votes vote down vote up
private void updateToLatestVersion() {
  Deque<Integer> versions = new ArrayDeque<>();
  versionQueue.drainTo(versions);

  if (!versions.isEmpty()) {
    int latestVersion = versions.getLast();
    final Collection<BaragonServiceState> newState = stateFetcher.fetchState(latestVersion);

    listenerContainer.forEach(new Function<BaragonStateListener, Void>() {

      @Override
      public Void apply(BaragonStateListener listener) {
        listener.stateChanged(newState);
        return null;
      }
    });
  }
}
 
Example 3
Source File: PipelineTest.java    From postgres-async-driver with Apache License 2.0 6 votes vote down vote up
@Test
public void connectionPoolPipelinesQueries() throws InterruptedException {
    int count = 5;
    double sleep = 0.5;
    Deque<Long> results = new LinkedBlockingDeque<>();
    long startWrite = currentTimeMillis();
    for (int i = 0; i < count; ++i) {
        pool.completeQuery("select " + i + ", pg_sleep(" + sleep + ")")
                .thenAccept(r -> results.add(currentTimeMillis()))
                .exceptionally(th -> {
                    throw new AssertionError("failed", th);
                });
    }
    long writeTime = currentTimeMillis() - startWrite;

    long remoteWaitTimeSeconds = (long) (sleep * count);
    SECONDS.sleep(2 + remoteWaitTimeSeconds);
    long readTime = results.getLast() - results.getFirst();

    assertThat(results.size(), is(count));
    assertThat(MILLISECONDS.toSeconds(writeTime), is(0L));
    assertThat(MILLISECONDS.toSeconds(readTime + 999) >= remoteWaitTimeSeconds, is(true));
}
 
Example 4
Source File: Solution7.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
public int[] maxSlidingWindow(int[] nums, int k) {
    int len = nums.length;
    if (len == 0) {
        return new int[0];
    }

    // 0 1 2 3 4 5 , k = 3
    //     0 1 2 3
    int[] res = new int[len - k + 1];
    // 存索引值,因为需要知道它什么时候应该被删除
    Deque<Integer> deque = new ArrayDeque<>();
    for (int i = 0; i < len; i++) {
        // 先考虑收缩左区间
        if (i >= k && deque.getFirst() == i - k) {
            deque.removeFirst();
        }

        while (!deque.isEmpty() && nums[deque.getLast()] <= nums[i]) {
            deque.removeLast();
        }
        deque.add(i);

        if (i >= k - 1) {
            res[i - k + 1] = nums[deque.getFirst()];
        }
    }
    return res;
}
 
Example 5
Source File: Solution.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
/**
 * 双端队列的做法
 *
 * @param nums
 * @param k
 * @return
 */
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];

    // 循环不变量:
    // queue 中的元素,如果先进来的元素比后进来的元素小,先进来的元素需要从对尾弹出以后,后进来的元素才进来
    // queue 首一定是当前滑动窗口内最大元素的索引

    Deque<Integer> queue = new LinkedList<>();
    for (int i = 0; i < len; i++) {
        if (i >= k && queue.getFirst() == i - k) {
            queue.removeFirst();
        }
        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;
}
 
Example 6
Source File: NavigatorService.java    From AssistantBySDK with Apache License 2.0 5 votes vote down vote up
private Deque<Integer> formatConjestionDistance(List<RoadConditionItem> conditionItems, int eIndex, double totalDistance) {
    Deque<Integer> dists = new ArrayDeque<Integer>();
    RoadConditionItem item;
    int t;
    double maxIndex = conditionItems.get(conditionItems.size() - 1).curItemEndIndex;
    for (RoadConditionItem conditionItem : conditionItems) {
        conditionItem.curItemEndIndex = (int) (conditionItem.curItemEndIndex / maxIndex * totalDistance);
    }
    for (int i = 0; i < eIndex; i++) {
        item = conditionItems.get(i);
        if (dists.size() == 0) {
            if (item.roadConditionType > RoadConditionItem.ROAD_CONDITION_TYPE_Straightway) {
                dists.offer(i == 0 ? item.curItemEndIndex : item.curItemEndIndex - conditionItems.get(i - 1).curItemEndIndex);
            }
        } else {
            t = dists.size();
            if ((t & 1) == 1) {//奇数,拥堵长度
                if (item.roadConditionType > RoadConditionItem.ROAD_CONDITION_TYPE_Straightway) {
                    dists.offer(dists.pollLast() + (item.curItemEndIndex - conditionItems.get(i - 1).curItemEndIndex));
                } else {
                    dists.offer((item.curItemEndIndex - conditionItems.get(i - 1).curItemEndIndex));
                }
            } else {//偶数,顺畅长度
                if (item.roadConditionType > RoadConditionItem.ROAD_CONDITION_TYPE_Straightway) {
                    if (dists.getLast() <= 100) {
                        dists.pollLast();
                        dists.offer(dists.pollLast() + (item.curItemEndIndex - conditionItems.get(i - 1).curItemEndIndex));
                    } else {
                        dists.offer((item.curItemEndIndex - conditionItems.get(i - 1).curItemEndIndex));
                    }
                } else {
                    dists.offer(dists.pollLast() + (item.curItemEndIndex - conditionItems.get(i - 1).curItemEndIndex));
                }
            }
        }
    }
    return dists;
}
 
Example 7
Source File: AbstractCompositeMetrics.java    From mapbox-events-android with MIT License 5 votes vote down vote up
/**
 * Adds value to the metric and occasionally creates new metric
 * if the delta is out of the exiting metric span.
 *
 * @param name name of the metric.
 * @param delta value to increment.
 */
public void add(String name, long delta) {
  long now = SystemClock.uptimeMillis();

  Metrics last;
  synchronized (this) {
    Deque<Metrics> metrics = getOrCreateMetrics(name.trim());
    if (now >= metrics.getLast().getEnd()) {
      metrics.add(nextMetrics(now, now + maxLength));
    }
    last = metrics.getLast();
  }
  last.add(delta);
}
 
Example 8
Source File: Logger.java    From rcrs-server with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static org.apache.log4j.Logger get() {
    Deque<org.apache.log4j.Logger> queue = LOG.get();
    if (queue.isEmpty()) {
        return LogManager.getRootLogger();
    }
    return queue.getLast();
}
 
Example 9
Source File: WiggleHelper.java    From Wiggle with Apache License 2.0 5 votes vote down vote up
@Override
protected Frame extractFrameToFixPosition(long delayMillis, Deque<Frame> frameDeque) {
    Frame last = frameDeque.getLast();
    Frame first = frameDeque.getFirst();
    long diffNanos = Math.abs(first.frameTimeNanos - last.frameTimeNanos);
    long diffMillis = TimeUnit.NANOSECONDS.toMillis(diffNanos);
    if (diffMillis >= delayMillis) {
        return frameDeque.pollFirst();
    }
    return first;
}
 
Example 10
Source File: LongestPathFinder.java    From megamek with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 11
Source File: Progress.java    From OSPREY3 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public long getEtaMs(Deque<Long> workLog, Deque<Long> timeMsLog, long totalWork) {
	
	// not enough data?
	if (workLog.size() < 2) {
		return -1;
	}
	
	// perform simple linear regression
	double sumxy = 0.0;
	double sumx = 0.0;
	double sumy = 0.0;
	double sumxsq = 0.0;
	Iterator<Long> workIter = workLog.iterator();
	Iterator<Long> timeIter = timeMsLog.iterator();
	while (workIter.hasNext()) {
		long work = workIter.next();
		long timeMs = timeIter.next();
		sumxy += work*timeMs;
		sumx += work;
		sumy += timeMs;
		sumxsq += work*work;
	}
	
	// solve for slope (a) and intercept (b)
	double a = (sumxy - sumx*sumy/workLog.size())/(sumxsq - sumx*sumx/workLog.size());
	double b = (sumy - a*sumx)/workLog.size();
	
	// extrapolate the finish time (y = ax+b), then compute the ETA
	double x = totalWork;
	return (long) (a*x + b) - timeMsLog.getLast();
}
 
Example 12
Source File: LinkedDequeTest.java    From multiway-pool with Apache License 2.0 4 votes vote down vote up
@Test(dataProvider = "emptyDeque", expectedExceptions = NoSuchElementException.class)
public void getLast_whenEmpty(Deque<SimpleLinkedValue> deque) {
  deque.getLast();
}
 
Example 13
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 14
Source File: XmlParserStream.java    From yangtools with Eclipse Public License 1.0 4 votes vote down vote up
private static boolean isElementList(final Deque<DataSchemaNode> childDataSchemaNodes) {
    final DataSchemaNode last = childDataSchemaNodes.getLast();
    return last instanceof ListSchemaNode || last instanceof LeafListSchemaNode;
}
 
Example 15
Source File: LinkedDequeTest.java    From concurrentlinkedhashmap with Apache License 2.0 4 votes vote down vote up
@Test(dataProvider = "emptyDeque", expectedExceptions = NoSuchElementException.class)
public void getLast_whenEmpty(Deque<SimpleLinkedValue> deque) {
  deque.getLast();
}
 
Example 16
Source File: LongestPathFinder.java    From megamek with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Deque<MovePath> doRelax(Deque<MovePath> v, MovePath mpCandidate, Comparator<MovePath> comparator) {
    if (mpCandidate == null)
        throw new NullPointerException();
    if (v == null) {
        return new ArrayDeque<>(Collections.singleton(mpCandidate));
    }
    MovePath topMP = v.getLast();

    /*
     * consider hexes travelled. If we enter the hex with different
     * hexes travelled then totally different paths will emerge
     */
    int dHT = topMP.getHexesMoved() - mpCandidate.getHexesMoved();
    if (dHT > 0) {
        /*
         * Current implementation of doRelax() assumes that v is sorted
         * in such way that this situation is impossible.
         */
        System.err.println(new IllegalStateException("Top Move Path moved more than Move Path Candidate."));
    }
    if (dHT < 0) {
        v.addLast(mpCandidate);
        return v;
    }

    // assert( topMP.getHexesMoved() == mpCandidate.getHexesMoved() );
    int dMP = topMP.getMpUsed() - mpCandidate.getMpUsed();
    if (dMP > 0) {
        /*
         * Current implementation of doRelax() assumes that v is sorted
         * in such way that this situation is impossible.
         */
        System.err.println(new IllegalStateException(
                "Top Move Path uses more MPs than Move Path Candidate. "
                + "while traveling the same distance"));
    }

    //assert( topMP thrust used is less or equal than candidates and hexesMoved are equal)
    if (!inAthmosphere) {
        return null; //there is no point considering hexes flown straight if we are not in athmo
    }

    //while in athmosphere we should consider paths that have higher thrust used but flew more hexes straight
    MoveStep topLastStep = topMP.getLastStep();
    MoveStep candidateLastStep = mpCandidate.getLastStep();
    int hs1 = topLastStep == null ? 0 : topLastStep.getNStraight();
    int hs2 = candidateLastStep == null ? 0 : candidateLastStep.getNStraight();
    int dHS = hs1 - hs2;

    if (-dHS > 0) {
        if (dMP >= 0) {
            System.err.println(new IllegalStateException(
                    "Top Move Path uses more MPs than Move Path Candidate and " +
                    "Top Move Path moves a shorter straight line distance."));
        }
        if (topLastStep != null && !topLastStep.dueFreeTurn()) {
            v.add(mpCandidate);
            return v;
        }
    }

    return null;
}
 
Example 17
Source File: LongestPathFinder.java    From megamek with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Deque<MovePath> doRelax(Deque<MovePath> v, MovePath mpCandidate, Comparator<MovePath> comparator) {
    if (mpCandidate == null) {
        throw new NullPointerException();
    }
    if (v == null) {
        return new ArrayDeque<>(Collections.singleton(mpCandidate));
    }
    while (!v.isEmpty()) { //we could get rid of this loop, since we require a proper comparator
        MovePath topMP = v.getLast();

        //standing up is always reasonable for mechs
        boolean vprone = topMP.getFinalProne(), eprone = mpCandidate.getFinalProne();
        if (vprone != eprone) {
            if (vprone) {
                break;
            } else {
                return null;
            }
        }
        if (!(topMP.getEntity() instanceof Tank)) {
            boolean vhdown = topMP.getFinalHullDown(), ehdown = mpCandidate.getFinalHullDown();
            if (vhdown != ehdown) {
                if (vhdown) {
                    break;
                } else {
                    return null;
                }
            }
        }
        /*
         * We require that the priority queue v of MovePath is sorted
         * lexicographically using product MPUsed x (-HexesMoved).
         */
        int topMpUsed = topMP.getMpUsed(), mpCMpUsed = mpCandidate.getMpUsed();

        if (topMpUsed > mpCMpUsed) {
            /*
             * topMP should have less or equal 'movement points used'
             * since it was taken from candidates priority queue earlier
             *
             * Current implementation of doRelax() assumes that v is
             * sorted in such way that this situation is impossible.
             */
            System.err.println(new IllegalStateException(
                    "Top Move Path uses more MPs than Move Path Candidate."));
            return null;
        } else {
            if (topMP.getHexesMoved() > mpCandidate.getHexesMoved()) {
                return null; //topMP path is longer and uses less or same mp.
            }
            if (topMP.getHexesMoved() == mpCandidate.getHexesMoved()) {
                //we want to preserve both forward and backward movements
                //that end in the same spot with the same cost.
                MoveStep topStep = topMP.getLastStep();
                boolean topBackwards = topStep != null && topStep.isThisStepBackwards();
                MoveStep mpCandStep = mpCandidate.getLastStep();
                boolean mpCandBackwars = mpCandStep != null && mpCandStep.isThisStepBackwards();
                if (!(topMP.getEntity() instanceof Infantry) && topBackwards != mpCandBackwars) {
                    break;
                }
                return null;
            }

            if (topMpUsed == mpCMpUsed) {
                //mpCandidate is not strictly better than topMp so we won't use it.
                return null;
            } else if (topMpUsed < mpCMpUsed) {
                //topMP travels less but also uses less movement points so we should keep it
                //and add mpCandidate to the list of optimal longest paths.
                break;
            }
        }
    }
    v.addLast(mpCandidate);
    return v;
}
 
Example 18
Source File: LithoViewTestHelper.java    From litho with Apache License 2.0 3 votes vote down vote up
/**
 * @see #findTestItems(LithoView, String)
 *     <p><strong>Note:</strong> If there is more than one element mounted under the given key,
 *     the last one to render will be returned.
 * @param lithoView The component view the component is mounted to.
 * @param testKey The unique identifier the component was constructed with.
 * @return Test item if found, null otherwise.
 * @throws UnsupportedOperationException If the e2e flag is not enabled in the configuration.
 */
@DoNotStrip
@Nullable
public static TestItem findTestItem(LithoView lithoView, String testKey) {
  final Deque<TestItem> items = lithoView.findTestItems(testKey);

  return items.isEmpty() ? null : items.getLast();
}