首页 > 其他 > 详细

Contiguous Subarrays

时间:2021-01-12 09:45:41      阅读:38      评论:0      收藏:0      [点我收藏+]

 

https://leetcode.com/discuss/interview-question/742523/facebook-prep-question-contiguous-subarrays-on-solution

 

 1 int[] countSubarrays(int[] arr) {
 2     int len = arr.length;
 3     
 4     Deque<Integer> stack = new ArrayDeque<>(); //index
 5     int[] leftCount = new int[len];
 6     //left[0] = 0
 7     stack.addLast(0);
 8     for(int i = 1; i<len; ++i) {
 9       int current = arr[i];
10       if(arr[stack.peekLast()]>current){
11         leftCount[i] = 0;
12         stack.addLast(i);
13         continue;
14       }
15       
16       while(!stack.isEmpty() && arr[stack.peekLast()]<current){
17         stack.removeLast();
18       }
19       int last = -1;
20       if(!stack.isEmpty()) {
21         last = stack.peekLast();
22       }
23       leftCount[i] = i - (last+1);
24       stack.addLast(i);
25     }
26     
27     stack.clear();
28     stack.addLast(len-1);
29     int[] rightCount = new int[len];
30     for(int i = len-2; i>=0; --i) {
31       int current = arr[i];
32       if(arr[stack.peekLast()]>current){
33         rightCount[i] = 0;
34         stack.addLast(i);
35         continue;
36       }
37       
38       while(!stack.isEmpty() && arr[stack.peekLast()]<current){
39         stack.removeLast();
40       }
41       int last = len;
42       if(!stack.isEmpty()) {
43         last = stack.peekLast();
44       }
45       rightCount[i] = last-1-i;
46       stack.addLast(i);
47     }
48     
49     int[] ret = new int[len];
50     for(int i = 0; i<len; ++i) {
51       ret[i] = leftCount[i] + rightCount[i] + 1;
52     }
53     return ret;
54   }

 

Contiguous Subarrays

原文:https://www.cnblogs.com/neweracoding/p/14265213.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!