496次大要素I *
https://leetcode.com/problems/next-greater-element-i/
タイトル説明
次の2つの配列が与えられ(重複なし) nums1
とnums2
場所nums1
の要素がのサブセットですnums2
。以下のためのすべての次に大きい番号検索nums1
の対応する場所での要素をnums2
。
番号の次のより多くx
では、nums1
その右側に第大きい番号ですnums2
。それは、出力が存在しない場合は-1
、この番号のために。
例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.
例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.
注意:
- すべての要素
nums1
とはnums2
ユニークです。 - 両方の長さ
nums1
とnums2
1000を超えないであろう。
C ++の実装1
検索num1
の各番号nums2
。まずにおける次の大きな数ハッシュテーブルが格納されているnums2
各番号に割り当てられたインデックスで、その後を探しnums1
、それぞれに数nums2
箇所idx
、そして最終的に次のより多くを見つけます。
この質問はまた、行う見るためにスタックを使用することができC++ 实现 2
、たとえば、解決することができ、スタック使用量がより一般的で、1019次グレーター・ノードにリンクされたリスト**この質問を。
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int, int> record;
for (int i = 0; i < nums2.size(); ++ i) record[nums2[i]] = i;
vector<int> res;
for (auto &n : nums1) {
auto idx = record[n];
auto greater = n;
for (int i = idx + 1; i < nums2.size(); ++ i) {
if (nums2[i] > greater) {
greater = nums2[i];
break;
}
}
if (greater != n) res.push_back(greater);
else res.push_back(-1);
}
return res;
}
};
C ++での2
使用スタックを達成する。ハッシュテーブルrecord
のレコードをnums2
NEGの存在下での各要素のために、それらの対応する位置NEGが横断した場合nums2
の処理、一時NEGが発生しない、要素がスタックに追加されなければなりません。
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int, int> record;
vector<int> res(nums1.size(), -1);
stack<int> st;
// record 保存了 nums2 中每个存在 NGE 的元素对应的 NGE 的索引
for (int i = 0; i < nums2.size(); ++ i) {
while (!st.empty() && nums2[i] > nums2[st.top()]) {
record[nums2[st.top()]] = i;
st.pop();
}
st.push(i);
}
for (int i = 0; i < nums1.size(); ++ i)
if (record.count(nums1[i]))
res[i] = nums2[record[nums1[i]]]; // 注意 record 中保存的是索引
return res;
}
};