classSolution{publicint[]dailyTemperatures(int[] temperatures){Stack<Integer> st =newStack<>();int[] res =newint[temperatures.length];
st.push(0);for(int i =1; i < temperatures.length; i++){if(temperatures[i]< temperatures[st.peek()]){
st.push(i);}elseif(temperatures[i]== temperatures[st.peek()]){
st.push(i);}else{while(!st.isEmpty()&& temperatures[i]> temperatures[st.peek()]){
res[st.peek()]= i - st.peek();
st.pop();}
st.push(i);}}return res;}}
496.下一个更大元素 I
学习文章链接:
思路:见代码
代码:
classSolution{publicint[]nextGreaterElement(int[] nums1,int[] nums2){Stack<Integer> st =newStack<>();int[] res =newint[nums1.length];Arrays.fill(res,-1);HashMap<Integer,Integer> map =newHashMap<>();for(int i =0; i < nums1.length; i++){
map.put(nums1[i], i);}
st.add(0);for(int i =1; i < nums2.length; i++){while(!st.isEmpty()&& nums2[st.peek()]< nums2[i]){if(map.containsKey(nums2[st.peek()])){Integer index = map.get(nums2[st.peek()]);
res[index]= nums2[i];}
st.pop();}
st.add(i);}return res;}}