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
相关推荐
dragoooon345 小时前
[优选算法专题六.模拟 ——NO.40~41 外观数列、数青蛙]
数据结构·算法·leetcode
一匹电信狗6 小时前
【C++】封装红黑树实现map和set容器(详解)
服务器·c++·算法·leetcode·小程序·stl·visual studio
flashlight_hi11 小时前
LeetCode 分类刷题:141. 环形链表
javascript·算法·leetcode
Kt&Rs12 小时前
11.9 LeetCode 题目汇总与解题思路
算法·leetcode
ゞ 正在缓冲99%…13 小时前
leetcode1547.切棍子的最小成本
数据结构·算法·leetcode·动态规划
2401_8414956413 小时前
【LeetCode刷题】移动零
数据结构·python·算法·leetcode·数组·双指针法·移动零
开心星人13 小时前
Leetcode hot100 Java刷题(二)
java·算法·leetcode
hn小菜鸡13 小时前
LeetCode 153.寻找旋转排序数组中的最小值
数据结构·算法·leetcode
蒙奇D索大17 小时前
【算法】递归算法的深度实践:深度优先搜索(DFS)从原理到LeetCode实战
c语言·笔记·学习·算法·leetcode·深度优先
一匹电信狗17 小时前
【C++11】右值引用+移动语义+完美转发
服务器·c++·算法·leetcode·小程序·stl·visual studio