2024-06-24力扣每日一题

链接:

503. 下一个更大元素 II

题意

循环数组,找出每个元素的往后最近且大于它的元素

今天没试暴力啊,大概率是过不了的

思路就是先找到最大的数,最大数的结果肯定是-1,然后倒着遍历数组,用一个栈来从大到小的存放数字,就可以很方便的得到离自身最近的比自己大的数字,同时由于是倒着遍历,所以栈内数字一定在当前遍历的数字之后

核心思路是,从后往前遍历时 ,后遍历到的数字(位置靠前)的 数字是可以完全替换掉先遍历到的数字(位置靠后)

实际代码:

c++ 复制代码
#include<bits/stdc++.h>
using namespace std;
vector<int> nextGreaterElements(vector<int>& nums)
{
    int maxIndex=-1;
    int lg=nums.size();
    stack<int>tMax;
    vector<int>ans(lg,0);
    
    for(int i=0;i<lg;i++)
    {
        if(maxIndex==-1 || nums[i]>nums[maxIndex])
        {
            maxIndex=i;
        }
    }
    ans[maxIndex]=-1;tMax.push(nums[maxIndex]);
    
    for(int i=1;i<lg;i++)
    {
        int mao=(maxIndex-i+lg)%lg;
        
        while(tMax.size() && tMax.top()<=nums[mao])
        {
            tMax.pop();
        }
        
        if(tMax.size())
        {
            ans[mao]=tMax.top();
        }
        else ans[mao]=-1;
        
        tMax.push(nums[mao]);
    }
    
    return ans;
}
int main()
{
    vector<int> nums;
    int temp;
    
    while(cin>>temp)
    {
        nums.push_back(temp);
    }
    
    vector<int>ans=nextGreaterElements(nums);
    int lg=ans.size();
    //cout<<"lg:"<<lg<<endl;
    for(int i=0;i<lg;i++)
    {
        cout<<"i:"<<ans[i]<<endl;
    }
    return 0;
}

限制:

  • 1 <= nums.length <= 104
  • -109 <= nums[i] <= 109
相关推荐
琢磨先生David4 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝4 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll4 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐4 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶5 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
im_AMBER5 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了5 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表
tyb3333335 天前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
踩坑记录5 天前
leetcode hot100 74. 搜索二维矩阵 二分查找 medium
leetcode
TracyCoder1235 天前
LeetCode Hot100(60/100)——55. 跳跃游戏
算法·leetcode