java - How to get the max number in all sliding windows of an array? -


given array of numbers , sliding window size, how maximal numbers in sliding windows?

for example, if input array {2, 3, 4, 2, 6, 2, 5, 1} , size of sliding windows 3, output of maximums {4, 4, 6, 6, 6, 5}. size of sliding window variable passed you.

a sliding window subarray of original array starts @ particular index. instance, @ index 0, size 3, it's first 3 elements. @ index 1, size 3, it's 2nd, 3rd , 4th element.

how solve in java or other programming language? or pseudocode, if desire.

(note: not homework question, question found on site have own solution want compare others, i'll post solution below afterwards too)

you can in o(n*log(w)), n size of array, , w size of sliding window.

use binary tree store first w numbers. following n-w steps, max value tree output, add element @ current position i tree, , remove element @ i-w tree. these operations o(log(w)), overall timing of o(n*log(w)):

int[] data = new int[] {2, 3, 4, 2, 6, 2, 5, 1}; int w = 3; treemap<integer,integer> counts = new treemap<integer,integer>(); (int = 0 ; != w ; i++) {     if (counts.containskey(data[i])) {         counts.put(data[i], counts.get(data[i])+1);     } else {         counts.put(data[i], 1);     } } (int = w ; != data.length ; i++) {     integer max = counts.lastkey();     system.out.println(max);     int tmp = counts.get(data[i-w])-1;     if (tmp != 0) {         counts.put(data[i-w], tmp);     } else {         counts.remove(data[i-w]);     }     if (counts.containskey(data[i])) {         counts.put(data[i], counts.get(data[i])+1);     } else {         counts.put(data[i], 1);     } } system.out.println(counts.lastkey()); 

demo on ideone.


Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -

c# - String.format() DateTime With Arabic culture -