Java中 Queue队列的用法及例子

it2022-05-08  6

1. Usage 用法

// "static void main" must be defined in a public class. public class Main { public static void main(String[] args) { // 1. Initialize a queue. Queue<Integer> q = new LinkedList(); // 2. Get the first element - return null if queue is empty. System.out.println("The first element is: " + q.peek()); // 3. Push new element. q.offer(5); q.offer(13); q.offer(8); q.offer(6); // 4. Pop an element. q.poll(); // 5. Get the first element. System.out.println("The first element is: " + q.peek()); // 7. Get the size of the queue. System.out.println("The size is: " + q.size()); } }

例 Moving Average from Data Stream

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

Example:

MovingAverage m = new MovingAverage(3); m.next(1) = 1 m.next(10) = (1 + 10) / 2 m.next(3) = (1 + 10 + 3) / 3 m.next(5) = (10 + 3 + 5) / 3 class MovingAverage { Queue<Integer> q; double sum = 0; int size; public MovingAverage(int s) { q = new LinkedList(); size = s; } public double next(int val) { if(q.size() == size){ sum = sum - q.poll(); } q.offer(val); sum += val; return sum/q.size(); } }

时间复杂度 O(1)

空间复杂度 O(N)


最新回复(0)