算法作业_7(2017.3.16第四周)

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.

解析:方法一:这道题给了我们一个数组,又给了该数组的一个子集合,让我们求集合中每个数字在原数组中右边第一个较大的数字。可以先采用暴力搜索,遍历子集合中的每一个数字,然后在原数组中找到这个数字,然后向右遍历,找到第一个大于该数字的数即可,代码如下:

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
        vector<int> res(findNums.size());
        for (int i = 0; i < findNums.size(); ++i) {
            int j = 0, k = 0;
            for (; j < nums.size(); ++j) {
                if (nums[j] == findNums[i]) 
                    break;
            }
            for (k = j + 1; k < nums.size(); ++k) {
                if (nums[k] > nums[j]) {
                    res[i] = nums[k];
                    break;
                }
            }
            if (k == nums.size()) 
                res[i] = -1;
        }
        return res;
        
}
};

方法二: 上面的方法稍做优化,用Map表先来建立每个数字和其坐标位置之间的映射,那么在遍历子集合中的数字时,就能直接定位到该数字在原数组中的位置,然后再往右边遍历寻找较大数即可:

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
       
        vector<int> res (findNums.size());
        unordered_map<int, int> m;
        
        for(int i = 0 ;i<nums.size();i++){
            m[nums[i]] = i ; 
        }
        
        for(int i = 0;i<findNums.size();i++){
            res[i]= -1;
            int start = m[findNums[i]];
            for(int j = start+1;j<nums.size();j++){
                if(nums[j]>nums[start]){
                    res[i]=nums[j];
                    break;
                }
            }
        }
        return res;
        
}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值