forked from ppsirker/dsalgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNextSmallInteger.java
45 lines (40 loc) · 970 Bytes
/
NextSmallInteger.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
For problem and solution description please visit the link below
http://www.dsalgo.com/2013/02/ArrayNextSmallElement.php.html
*/
package com.dsalgo;
import java.util.LinkedList;
public class NextSmallInteger
{
/**
* given an array form another array where each element of previous array is replaced with
* its next minimum number in the array
* @param args
*/
public static void main(String[] args)
{
int[] input={3,4,5,2,7,5,7,3,8,2,5,7,9,1,3};
int[]output=new int[input.length];
LinkedList<Integer> stack=new LinkedList<Integer>();
for(int i=input.length-1;i>=0;--i)
{
int currentNum=input[i];
if(stack.peek()==null)
{
output[i]=0;
stack.push(currentNum);
continue;
}
while(stack.size()!=0 && stack.peek()>=currentNum)
{
stack.pop();
}
output[i]=stack.peek()==null?0:stack.peek();
stack.push(currentNum);
}
for(int i=0;i < output.length;++i)
{
System.out.print(output[i]+",");
}
}
}