496. Under a greater element!

next-greater-element-i

Title Description
Given two arrays nums1 no duplicate elements and nums2, wherein nums1 is a subset of nums2. Nums1 found under each element in a nums2 is larger than the value.

The next higher element numbers refer nums1 x x x corresponds to the first element is larger than the right position in the nums2. If not, the position output corresponding to -1.

Example 1:

Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [1,3, -1]
Explanation:
For num1 in figure 4, you are not in the second array to find the next larger number, and therefore the output 1.
For num1 in figures 1, the next higher number in a second array number 1 on the right is three.
For num1 in the number 2, the second array is no next larger number, and therefore the output 1.

Example 2:

Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3, -1]
Explanation:
For num1 in the number 2, the second array to the next higher number 3.
For num1 in figures 4, the second array is no next larger number, and therefore the output 1.

note:

nums1 and nums2 all elements are unique.
nums1 and nums2 array size is not more than 1,000.

Explained
with reference to the illustrated solution to a problem of official

Code

package pid496;
import java.util.HashMap;
import java.util.Stack;

public class Solution {
	public int[] nextGreaterElement(int[] nums1,int[] nums2){
		/*
		 * 务必注意:两个数组中均没有重复元素
		 */
		Stack<Integer> stack = new Stack<>();
		HashMap<Integer,Integer> map = new HashMap<>();
		
		//先不理会nums1,在nums2中找到各元素对应的下一个更大元素值,并存入map
		for(int i=0;i<nums2.length;i++){
			if(stack.isEmpty()){
				stack.push(nums2[i]);
				continue;
			}
			
			if(nums2[i]<=stack.peek()){
				stack.push(nums2[i]);
			}else{
				//有可能当前元素是栈中多个元素的下一个更大元素
				while(!stack.isEmpty() && nums2[i]>stack.peek()){
					//!stack.isEmpty()在前,优先保证栈不为空;若栈空不执行后一个判断
					int val = nums2[i];
					int key = stack.pop();
					map.put(key, val);
				}
				//给比nums[i]小的元素设置好下一个更大元素nums[i]后,还需要将nums[i]入栈求它自己的下一个更大元素
				stack.push(nums2[i]);
			}
		}
		
		//stack中剩余的那些数没有实际的下一个最大元素,因此它们的下一个最大元素是-1
		while(!stack.isEmpty()){
			int val = -1;
			int key = stack.pop();
			map.put(key, val);
		}
		
		/*
		 * 注意:nums1是nums2的一个子集,所以nums1中的元素必然存在于nums2中。
		 * 在map表中查nums1中的元素的下一个最大元素。为了节省内存空间,这里采用原地操作。
		 */
		for(int i=0;i<nums1.length;i++){
			int val = map.get(nums1[i]);
			nums1[i] = val;
		}
		
		return nums1;
	}
}

Performance
Performance

Published 75 original articles · won praise 0 · Views 1506

Guess you like

Origin blog.csdn.net/qq_34087914/article/details/104120082