496. Next Greater Element I

来源:互联网 发布:淘宝卖蚕丝被 编辑:程序博客网 时间:2024/05/19 10:10

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.
这道题主要就是通过循环先在nums数组里面找到对应的值,然后再在这个位置的后面找一找比它大的值,如果找不到就返回-1,还是比较直接的一个思路。同时用一个新的vector去存储数据
代码如下:

class Solution {public:    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {        vector<int>result;        for(int i=0;i<findNums.size();i++){            bool flag=false;            for(int j=0;j<nums.size();j++){                if(j==nums.size()-1){                    break;                }                if(findNums[i]==nums[j]){                    int m=j+1;                    while(m<=nums.size()-1)                    {                        if(nums[m]>findNums[i]){                            result.push_back(nums[m]);                            flag=true;                            break;                        }                        m++;                    }                }            }            if(!flag){                result.push_back(-1);            }        }        return result;    }};
原创粉丝点击