下一个更大的元素1
题目
给定两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。
nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出 -1 。
示例
输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
输出: [-1,3,-1]
解释:
对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。
对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。
对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1。
思路
- 使用栈,遍历数组nums2 ,判断当前元素是否大于栈顶的元素,如果大于则记录到哈希表中,同时栈顶元素出栈,直到栈为空或当前元素小于栈顶元素,则入栈。
- 然后遍历num1,哈希表不能找到用-1,能找到的用表中的。
代码
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int,int> my_map;
vector<int> res;
stack<int> my_stk;
for ( auto& n : nums2 ) {
if ( my_stk.empty() ) {
my_stk.push( n );
continue;
}
while ( !my_stk.empty() && n > my_stk.top() ) {
my_map[my_stk.top()] = n;
my_stk.pop();
}
my_stk.push( n );
}
for ( auto& n : nums1 ) {
if ( my_map.count( n ) > 0 ) {
res.push_back( my_map[n] );
}
else {
res.push_back( -1 );
}
}
return res;
}
};
下一个更大的元素2
题目
给定一个循环数组(最后一个元素的下一个元素是数组的第一个元素),输出每个元素的下一个更大元素。数字 x 的下一个更大的元素是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1。
示例1
输入: [1,2,1]
输出: [2,-1,2]
解释: 第一个 1 的下一个更大的数是 2;
数字 2 找不到下一个更大的数;
第二个 1 的下一个最大的数需要循环搜索,结果也是 2。
思路
- 这道题和1的区别是循环数组,以及数组元素可以重复。
- 解决循环数组的方法是,遍历两边数组。
- 重复导致不能在数组中保存元素本身,而是放入元素的索引,这样每次用当前元素和栈顶索引代表的元素进行比较。如果当前栈顶索引代表的数小于当前遍历数组的数,就可以对栈顶索引位置的结果填入当前数。
代码
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
vector<int> res( nums.size(), -1 );
stack<int> my_stk;
int cnt = 2;
while ( cnt-- ) {
for ( int i = 0; i < nums.size(); ++i ) {
while ( !my_stk.empty() && nums[my_stk.top()] < nums[i] ) {
res[my_stk.top()] = nums[i];
my_stk.pop();
}
my_stk.push( i );
}
}
return res;
}
};
下一个更大的元素3
题目
给定一个32位正整数 n,你需要找到最小的32位整数,其与 n 中存在的位数完全相同,并且其值大于n。如果不存在这样的32位整数,则返回-1。
示例1
输入: 12
输出: 21
示例2
输入: 21
输出: -1
思路
- 转成string,然后查找下一个组合。从后先前遍历字符串,找到第一个逆序字符对,即a位置的数小于后一个数字。然后再从末尾遍历,找到第一个大于a位置的元素b位置。交换a、b。然后把a后面进行排序。
代码
class Solution {
public:
int nextGreaterElement(int n) {
int res = -1;
string str_n = to_string( n );
// 从右向左遍历
int index = str_n.size() - 2;
while ( index >= 0 && str_n[index] >= str_n[index+1]) {
--index;
}
if ( index >= 0 ) {
int right = str_n.size() - 1;
while ( right > index && str_n[right] <= str_n[index] ) {
--right;
}
swap( str_n[index], str_n[right] );
sort( str_n.begin() + index + 1, str_n.end() );
res = str2Int( str_n );
}
return res;
}
int str2Int( string& str ) {
long long res = 0;
for ( auto& c : str ) {
int num = c - '0';
res = res * 10 + num;
}
if ( res > INT_MAX ) {
res = -1;
}
return res;
}
};