496. Next Greater Element I
阿新 • • 發佈:2020-06-27
You are given two arrays(without duplicates)nums1
andnums2
wherenums1
’s elements are subset ofnums2
. Find all the next greater numbers fornums1
's elements in the corresponding places ofnums2
.
The Next Greater Number of a numberxinnums1
is the first greater number to its right innums2
. If it does not exist, output -1 for this number.
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2]. Output: [-1,3,-1] Explanation: For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1. For number 1 in the first array, the next greater number for it in the second array is 3. For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
Example 2:
Input: nums1 = [2,4], nums2 = [1,2,3,4]. Output: [3,-1] Explanation: For number 2 in the first array, the next greater number for it in the second array is 3. For number 4 in the first array, there is no next greater number for it in the second array, so output -1.
Note:
- All elements in
nums1
nums2
are unique. - The length of both
nums1
andnums2
would not exceed 1000.
class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { int n1 = nums1.length; int n2 = nums2.length; int[] res = new int[n1]; Arrays.fill(res, -1); // List<Integer> list1 = new ArrayList(); // for(int i = 0; i < n1; i++) list1. for(int i = 0; i < n1; i++){ int t = nums1[i]; int j = 0; while(nums2[j] != t) j++; j++; for(; j < n2; j++){ if(nums2[j] > t){ res[i] = nums2[j]; break; } } } return res; } }
什麼狗jb描述,next greater number是說,nums1的element在nums2找到後,往右找有沒有比它更大的,沒有就是-1
class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { Map<Integer, Integer> map = new HashMap(); Stack<Integer> stack = new Stack(); for(int i: nums2){ while(!stack.isEmpty() && stack.peek() < i){ map.put(stack.pop(), i); } stack.push(i); } for(int i = 0; i < nums1.length; i++){ nums1[i] = map.getOrDefault(nums1[i], -1); } return nums1; } }
2. O(n)
問的實際上是nums2的next greater number,用stack維持一個decrease的數們,如果當前比peek大,那就pop所有比peek小的,他們的ngn就是當前
用map存放每個數對應的ngn。