Given two arrays nums1 and nums2 without repeating elements, where nums1 is a subset of nums2. Find the next greater value in nums2 for each element in nums1.
The next greater element of the number x in nums1 is the first element greater than x to the right of the corresponding position of x in nums2. If it does not exist, the corresponding position outputs -1.
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For the number 4 in num1, you cannot The next higher number is found in the second array, so -1 is output.
For number 1 in num1, the next larger number to the right of number 1 in the second array is 3.
For number 2 in num1, there is no next larger number in the second array, so -1 is output.
Example 2:
Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
For number 2 in num1, the next in the second array The larger number is 3.
For the number 4 in num1, there is no next larger number in the second array, so -1 is output.
Note:
1. All elements in nums1 and nums2 are unique.
2. The array size of nums1 and nums2 is not more than 1000.
See: https://leetcode.com/problems/next-greater-element-i/description/
C++:
method one:
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; } };
Method Two:
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] > findNums[i]) { res[i] = nums[j]; break; } } } return res; } };
Reference: http://www.cnblogs.com/grandyang/p/6399855.html