115、下一个更大元素

题目描述
给定两个没有重复元素的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。

nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出-1。

示例 1:

输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
输出: [-1,3,-1]
解释:
对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。
对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。
对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1。
示例 2:

输入: nums1 = [2,4], nums2 = [1,2,3,4].
输出: [3,-1]
解释:
对于num1中的数字2,第二个数组中的下一个较大数字是3。
对于num1中的数字4,第二个数组中没有下一个更大的数字,因此输出 -1。
注意:

nums1和nums2中所有元素是唯一的。
nums1和nums2 的数组大小都不超过1000。

比较简单的一道题,首先外层循环是nums1(子集),内存需要有一个循环找到和外层的i下标相等的下标
直接上代码吧这样简单易懂

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        		for (int i = 0; i < nums1.length; i++) {
		//	System.out.println("nums1的循环次数    "+i);
			int tem = nums1[i];
			int i1 = 0;
			for (i1 = 0; i < nums2.length; i1++) {
				if(nums2[i1] == tem)
					break;
			}
		//	System.out.println("与tem相等的nums2下标" + i1);
			if(i1 == nums2.length -1 ){
				nums1[i] = -1;
			}else {
				//找下一个大的值
				for (int j = i1 + 1; j < nums2.length; j++) {
					if(nums2[j] > tem){
						nums1[i] = nums2[j];
						break;
					}
				}
				if(tem == nums1[i])
					nums1[i] = -1;
			}
			
		}
		
		return nums1;
    }
}

排名靠前的代码,其实这个类似于之前的奖牌题目,数组的下标对应的是值,而存放的是下一个大于坐标的值,并且需要注意的是如果nums1的长度为0那么返回的是长度为零的数组,不能为null,否则会出错。

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        if (nums1.length == 0)
            return new int[0];
        int length1 = nums1.length;
        int length2 = nums2.length;
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < length2; i++){
            max = Math.max(max, nums2[i]);
        }
        
        int[] ans = new int[length1];
        int[] temp = new int[max + 1];
        for (int i = 0; i < max + 1; i++){
            temp[i] = -1;
        }
        // Arrays(temp, -1);
        for (int i = 0; i < length2; i++){
            for (int j = i + 1; j < length2; j++){
                if (nums2[j] > nums2[i]){
                    temp[nums2[i]] = nums2[j];
                    break;
                }
            }
        }
        
        for (int i = 0; i < length1; i++)
            ans[i] = temp[nums1[i]];
        
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34446716/article/details/85134225