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;
        }
  • 相关阅读:
    使用Python验证常见的50个正则表达式
    空气开关为何叫空气开关?它跟空气有何关系?
    YOLO 算法最全综述:从 YOLOv1 到 YOLOv5
    深入理解部分 SQL 语句执行慢的原因
    KNN(k-nearest-neighbor)算法
    聚类分析方法
    SQL Database学习笔记
    statistic学习笔记
    MapReduce中的排序
    weka打开提示内存不足的解决方法
  • 原文地址:https://www.cnblogs.com/insaneXs/p/6376641.html
Copyright © 2011-2022 走看看