剑指offer62 圆圈中最后剩下的数字

剑指offer62 圆圈中最后剩下的数字

     0, 1, …, n-1这n个数字(n>0)排成一个圆圈,从数字0开始每次从这个圆圈里删除第m个数字。

     求出这个圆圈里剩下的最后一个数字。

样例

输入:n=5 , m=3
输出:3

思路1

     创建一个vector nums 保存0-n-1数值,模拟环形链表,然后循环依次删除第m位置上的数值。时间复杂度为O(mn),空间复杂度为O(n);

AcWing-82 C++ code

class Solution {
public:
    int lastRemaining(int n, int m){
        if(n < 1 || m < 1){
            return -1;
        }
        vector<int> nums;
        for(int i = 0; i < n; i++){
            nums.push_back(i);
        }
        
        int currentIndex = 0;
        int nextIndex = 0;
        
        while(n > 1){
            int time = 1;
            while(time < m){
                time++;
                currentIndex++;
                if(currentIndex >= nums.size()){
                    currentIndex = 0;
                }
            }
            nums.erase(nums.begin() + currentIndex);
            if(currentIndex >= nums.size()){
                currentIndex = 0;
            }
            n--;
        }
        return nums[0];
    }
};

思路2

     balabala…emmm,时间复杂度为O(n),空间复杂度为O(1)。

AcWing-82 C++ code

class Solution {
public:
    int lastRemaining(int n, int m){
        if(n < 1 || m < 1){
            return -1;
        }
        int last = 0;
        for(int i = 2; i <= n; i++){
            last = (last + m) % i;
        }
        return last;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值