496. 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.

问题描述: 题目给出了两个无重复元素的数组nums1,nums2,其中nums1是nums2的子数组。要求得到一个长度与nums1相同,并且由与nums1元素对应的nums2元素的下一个较大元素所组成的数组,若不存在比子数组元素大的情况返回-1。

个人解题思路:1.定位元素相同的数组位置。2. 查找第一个大于所要查找元素的值,否则返回-1。一开始想图方便用Array.sort(int[] nums)与Array.binarySearch(int[] nums,int key),利用排序和查找方法来定位值出现位置,却忽略了此时经过排序后的数组,其元素顺序已经改变。

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {

                for( int i = 0; i < nums1.length; ++i){
                    int j = 0;
                    for(;j < nums2.length; ++j){//若在循环体中定义j,则是循环中的局部变量,退出循环时,这个变量会被回收。
                        if(nums2[j] == nums1[i])                            
                            break;//定位相等位置

                    }
                    int exch = nums1[i];
                    nums1[i] = -1;

                    for(++j; j < nums2.length; ++j){
                        if(nums2[j] > exch){//出现了直接用nums2[j] >nums2[j-1] 的错误,忽略了j在变化。
                            nums1[i] = nums2[j];
                            break;
                        }
                    }
                }
                return nums1;
    }
}

运行时间为14ms,运行速度较慢。

范例解决方法

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        if(nums1.length == 0) return new int[]{};
        int[] res = new int[nums1.length];
        int max = Integer.MIN_VALUE;
        for(int num : nums2){
            if(max < num) max = num;
        }
        int[] map = new int[max + 1];
        Arrays.fill(map, -1);
        for(int i = 0 ; i < nums2.length ; i ++){
            map[nums2[i]] = i;
        }
        for(int i = 0 ; i < nums1.length ; i ++){
            if(nums1[i] >= max) res[i] = -1;
            else{
                int index = map[nums1[i]];
                while(++index < nums2.length){
                    if(nums2[index] > nums1[i]){
                        res[i] = nums2[index];
                        break;
                    }
                }
                if(res[i] == 0) res[i] = -1;
            }
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值