496. Next Greater Element I

链接

496. Next Greater Element I

题意

给定两个数组(无重复数字)nums1和nums2,其中nums1是nums2的子集,找出所有nums1中元素在nums2中相对应位置之后的第一个较大数,不存在则表示为-1。
例如:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
4在nums2中后面没有比4大的,所以输出-1
1在nums2中,后面3是第一个比1大的,输出3
2在nums2中,后面没有元素了,所以输出-1

思路

遍历nums1,同时在nums2中得到该数的位置,然后再从nums2中该位置进行遍历,找出第一个较大数即可。

代码

Java:

public class Solution {
    public int[] nextGreaterElement(int[] findNums, int[] nums) {
        int[] ans = new int[findNums.length];
        for (int i = 0; i < findNums.length; i++) {
            for (int j = 0; j < nums.length; j++) {
                if (findNums[i] == nums[j]) {
                    for (int k = j; k < nums.length; k++) {
                        if (nums[k] > findNums[i]) {
                            ans[i] = nums[k];
                            break;
                        }
                        ans[i] = -1;
                    }
                }
            }
        }
        return ans;
    }
}

总结

  1. 效率不高(Your runtime beats 19.48% of java submissions)
原文地址:https://www.cnblogs.com/zyoung/p/6565476.html