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;
        }
  • 相关阅读:
    模块cv2的用法
    调整弹出对话框在ASP.NET应用程序的大小
    xaf 自定义登陆页
    xaf 修改主页logo
    显示一个列表视图图表
    双击直接编辑状态
    xaf 富文本框添加方法
    用户 'NT AUTHORITYIUSR' 登录失败
    C# 中的INotifyPropertyChanged
    线程间操作无效: 从不是创建控件“txtreceive”的线程访问它。
  • 原文地址:https://www.cnblogs.com/insaneXs/p/6376641.html
Copyright © 2011-2022 走看看