Next Greater Element II

针对LeetCode中关于循环数组寻找每个元素的下一个更大数值的问题,本文介绍了一种通过复制数组来模拟循环特性的解决方案,并给出了具体的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目来源LeetCode

Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn’t exist, output -1 for this number.

解题思路:将数组复制两遍来进行circular,然后再进行比较找出下一个最大元素,具体代码如下:

class Solution {
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
        vector<int>double_nums;
        vector<int>results;
        int l = nums.size();
        for(int i = 0; i < l; i++){
            double_nums.push_back(nums[i]);
        }
        for(int i = 0; i < l; i++){
            double_nums.push_back(nums[i]);
        }
        for(int i = 0; i < l; i++){
            for(int j = i; j <= i+l; j++){
                if(double_nums[i] < double_nums[j]){
                    results.push_back(double_nums[j]);
                    break;
                }
                else if(j == i+l && double_nums[i] >= double_nums[j]){
                    results.push_back(-1);
                    break;
                }
            }
        }
        return results;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值