[Leetcode 496] Next Greater Element I

作者 Shilei Tian 日期 2017-02-07
[Leetcode 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.

Example 1:

Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
For number 1 in the first array, the next greater number for it in the second array is 3.
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.

Example 2:

Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
For number 2 in the first array, the next greater number for it in the second array is 3.
For number 4 in the first array, there is no next greater number for it in the second array, so output -1.

Note:

  1. All elements in nums1 and nums2 are unique.
  2. The length of both nums1 and nums2 would not exceed 1000.

解题思路

根据题目的描述,我们很容易就写出下面的代码:

class Solution {
public:
vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
vector<int> ret;
for (auto findNum : findNums) {
int index = indexOf(nums, findNum);
bool found = false;
for (int i = index + 1; i < nums.size(); ++i) {
if (nums[i] > findNum) {
ret.push_back(nums[i]);
found = true;
break;
}
}
if (!found) {
ret.push_back(-1);
}
}
return ret;
}
private:
int indexOf(const vector<int>& nums, int target) {
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] == target) {
return i;
}
}
return -1;
}
};

提交后运行时间为 16 ms,时间复杂度应该为 $O(m \times n)$。那么我们能不能优化这个呢?网友提供的答案中有一个 $O(m)$ 的值得参考。

观察:考虑一个递减的序列,例如 [5, 4, 3, 2, 1, 6],那么对于 [5, 4, 3, 2, 1] 而言,下一个较大的元素都是 6,因为 [5, 4, 3, 2, 1] 都比 6 小。如果这个序列换成 [7, 4, 3, 2, 1, 6],那么 [4, 3, 2, 1] 的下一个较大的元素都是 6,而 7 的是 -1

那么有了上面的观察,我们可以想到,我们在遍历 nums2 的时候可以保存递减的序列,当遇到一个元素比我们递减序列中最后一个元素要大时,那么我们递减序列中比该元素小的元素的下一个较大的元素就可以确定了。由于我们都只操作递减序列的最后几个元素,因此用栈来实现这个序列是再合适不过的了。

具体的代码如下:

class Solution {
public:
vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
unordered_map<int, int> next;
stack<int> st;
for (auto num : nums) {
if (st.empty()) {
st.push(num);
} else {
if (num < st.top()) {
st.push(num);
} else {
while (!st.empty() && st.top() < num) {
next[st.top()] = num;
st.pop();
}
st.push(num);
}
}
}
while (!st.empty()) {
next[st.top()] = -1;
st.pop();
}
vector<int> ret;
for (auto findNum : findNums) {
ret.push_back(next[findNum]);
}
return ret;
}
};

运行时间为 12 ms,时间复杂度为 $O(n)$,这里 $n$ 是 nums2 的长度。