题意:数组
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
给你两个数组,为数组1和数组2,数组1为数组2的子集。找出数组1的每个元素在数组2中对应的元素a,而后找到元素a后侧第一个比a大的数构成一个数组,便是咱们须要的答案。若是不存在,则为-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.
思路一:
遍历两个数组,由于数组1是数组2的子集,我选择只遍历一次数组2而去屡次遍历数组1。并缓存对应的下标和数字,用来找到答案,可是这种作法效率不高。
public int[] nextGreaterElement(int[] findNums, int[] nums) { if(findNums == null){ return null; } int[] res = new int[findNums.length]; Arrays.fill(res, -1); List<Integer> cacheIndex = new LinkedList<Integer>(); List<Integer> cacheNum = new LinkedList<Integer>(); for(int i=0; i<nums.length; i++){ int num = nums[i]; for(int j=cacheNum.size() - 1; j>= 0; j--){ if(cacheNum.get(j) < num){ res[cacheIndex.get(j)] = num; cacheIndex.remove(j); cacheNum.remove(j); } } for(int j=0; j<findNums.length; j++){ if(findNums[j] == num){ cacheNum.add(num); cacheIndex.add(j); break; } } } return res; }