LeetCode 496. 下一个更大元素I

496. 下一个更大元素I

基本思路

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int[] res = new int[nums1.length];
        int index = 0;
        for(int i=0; i<nums1.length; i++){
            for(int j=0; j<nums2.length; j++){//遍历2,找到与1相同的数就记录index
                if(nums1[i] == nums2[j]){
                    index = j;
                    break;
                }
            }
            for(int k=index; k<nums2.length; k++){//判断2中右边第一个比1大的数
                if(nums2[k] > nums1[i]) {
                    res[i]=nums2[k];
                    break;
                }
                else{res[i]=-1;}
            }
        }
        return res;
    }
}

优化

在遍历2中找1的方法可以使用空间换时间的方法:

  1. 找到2的最大值
  2. 建立一个长度为最大值+1的数组bitmap,把2的值当作index放入到数组中,并为数组填充等值的数
  3. 比较2中比1大的数的起始点以bitmap[nums1[i]]+1作为起点即可
class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int l1 = nums1.length, l2 = nums2.length;
        int[] result = new int[l1];

        int max = 0;
        for (int i = 0; i < l2; i++)//步骤1
            if (nums2[i] > max)
                max = nums2[i];

        int[] bitmap = new int[max + 1];
        for (int i = 0; i < l2; i++)//步骤2
            bitmap[nums2[i]] = i;
        

        for (int i = 0; i < l1; i++) {//判断2中右边第一个比1大的数
            int n1 = nums1[i], m = -1;
            int idx = bitmap[n1];
            for (int j = idx + 1; j < l2; j++)
                if (nums2[j] > n1) {
                    m = nums2[j];
                    break;
                }
            result[i] = m;
        }

        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/u014239185/article/details/86150881