Next Greater Element I

題意:數組

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;
    }
相關文章
相關標籤/搜索