-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode503.java
More file actions
61 lines (53 loc) · 1.6 KB
/
Copy pathleetcode503.java
File metadata and controls
61 lines (53 loc) · 1.6 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package leetcode;
import java.util.*;
public class leetcode503 {
public static void main(String[] args) {
new leetcode503().nextGreaterElements(
new int[]{
1,2,1
}
);
}
//贪心法相对简单
public int[] nextGreaterElements(int[] nums) {
int res[]=new int[nums.length];
Arrays.fill(res,-1);
for (int i = 0; i <nums.length ; i++) {
for (int j=i;j<nums.length;j++){
if (nums[i]<nums[j]){
res[i]=nums[j];
break;
}
if (j==nums.length-1){
for (int k = 0; k <i ; k++) {
if (nums[i]<nums[k]){
res[i]=nums[k];
break;
}
if (k==i-1){
res[i]=-1;
}
}
}
}
}
return res;
}
//单调栈
public int[] SnextGreaterElements(int[] nums) {
Deque<Integer> stack = new ArrayDeque<>();
int len = nums.length;
int[] res = new int[len];
Arrays.fill(res, -1);
for (int i = 0; i < 2 * len; i++) {
int num = nums[(i+len) % len]; //关键步骤
while (!stack.isEmpty() && num > nums[stack.peek()]) {
res[stack.pop()] = num;
}
// use for second round
if (i < len) stack.push(i);
if (stack.isEmpty()) break;
}
return res;
}
}