zoukankan      html  css  js  c++  java
  • 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.

    给你两个数组,为数组1和数组2,数组1为数组2的子集。找出数组1的每一个元素在数组2中对应的元素a,然后找到元素a后侧第一个比a大的数构成一个数组,即是我们需要的答案。如果不存在,则为-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.

    思路一:
    遍历两个数组,因为数组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;
        }
  • 相关阅读:
    android studio导出apk
    Android开发入门经典实例
    L1-Day32
    L1-Day33
    L1-Day30
    Oracle中的null与空字符串''的区别
    Oracle中的job(定时任务)
    Oracle中的加解密函数
    LeetCode33题——搜索旋转排序数组
    Oracle中的DBMS_LOCK包的使用
  • 原文地址:https://www.cnblogs.com/insaneXs/p/6376641.html
Copyright © 2011-2022 走看看