You are given two arrays (without duplicates) nums1
and nums2
where nums1
’s elements are subset of nums2
. Find all the next greater numbers for nums1
's elements in the corresponding places of nums2
.數組
The Next Greater Number of a number x in nums1
is the first greater number to its right in nums2
. If it does not exist, output -1 for this number.this
Example 1:
spa
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:
code
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:
blog
nums1
and nums2
are unique.nums1
and nums2
would not exceed 1000.我用兩種方法解決這個問題。轉載註明出處:http://www.cnblogs.com/wdfwolf3/,謝謝。索引
1.時間複雜度O(m*n),8ms。思路很簡單,對於每一個子集合元素去遍歷父集合,查找大於它的第一個元素。element
public int[] nextGreaterElement(int[] findNums, int[] nums) { //ans數組存放結果 int[] ans = new int[findNums.length]; //便利數組findNums中的元素 for (int i = 0; i < findNums.length; i++) { int start = 0; //start索引從頭開始遍歷nums查找當前元素在nums中的位置 while (findNums[i] != nums[start]){ start++; } //從start位置開始向後查找第一個比當前元素大的值,並賦值到ans數組中 for (; start < nums.length; start++) { if(nums[start] > findNums[i]){ ans[i] = nums[start]; break; } } //若是start到達nums末尾,說明沒有找到大於當前元素的值,賦值-1到ans數組中 if(start == nums.length){ ans[i] = -1; } } return ans; }
2.時間複雜度O(m*n),空間複雜度O(n),11ms。利用一個棧來查找父集合中每一個元素的Next Greater Element,找到了就存放到HashMap中,最後遍歷子集合,若是HashMap中沒有說明不存在,賦值-1。get
public int[] nextGreaterElement(int[] findNums, int[] nums) { //輔助棧,存放待查找結果的元素,查找到的當即出棧 Stack<Integer> stack = new Stack<>(); //key存放元素,value存放找到的第一個大於它的值 Map<Integer, Integer> map = new HashMap<>(); //當棧頂元素大於當前元素時,入棧;當棧頂元素小於當前元素時,說明棧頂元素找到了第一個大於的值,出棧,而後繼續出棧直到棧頂元素大於當前元素,將當前元素入棧。 for (int i = 0; i < nums.length; i++) { while(!stack.isEmpty() && stack.peek() < nums[i]){ map.put(stack.pop(), nums[i]); } stack.push(nums[i]); } //ans數組存放結果 int[] ans = new int[findNums.length];
//遍歷findNums,在map中查找結果,不存在說明沒有大於它的第一個元素,賦值爲-1 for (int i = 0; i < findNums.length; i++) { ans[i] = map.getOrDefault(findNums[i], -1); } return ans; }