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;
        }
  • 相关阅读:
    idea最新注册码
    pycharm中可以运行脚本(只在控制台运行,Debugger不运行,设置的断点没用)但是不能debug脚本
    VSCode 云同步扩展设置 Settings Sync 插件
    gist.github.com 无法访问解决办法,亲测永远有效!
    C# HttpWebRequest httpclient
    C# 图片处理
    powerdesigner逆向工程生成PDM时的列注释
    Ocelot网关治理
    Consul服务注册与发现
    CentOS 使用DVD1_DVD2作为本地离线的更新源
  • 原文地址:https://www.cnblogs.com/insaneXs/p/6376641.html
Copyright © 2011-2022 走看看