496. Next Greater Element I

来源:互联网 发布:审批工作流数据库设计 编辑:程序博客网 时间:2024/06/07 00:31

问题: 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;    }}
原创粉丝点击