剑指offer - 62.圆圈中最后剩下的数字

(今天特别开心,拿到了一个心仪的offer,之前一直不太顺利,恭喜,但浪费了一下午,逛b站去了。。)
先还是把基础的算法题还是刷一下吧,这类型的博客网上有很多很多,不过大多是抄书上的代码,我想自己写一下。可能不一定严谨,但基本功能会实现。
慢慢的尝试有思路后能够自己写出代码来。
(这个题目原本想直接用链表写的,但是因为输入n个数构成n个节点后不好链接,每个节点需要一个对象名,没写成,以后再改)

在这里插入图片描述

#include <iostream>
#include <vector>  
#include<algorithm>
#include<list>
using namespace std;

int main()
{
	int n, m;
	cin >> n >> m;
	list<int> num;
	for (int i = 0; i < n; i++) {
		num.push_back(i);
	}
	int i = 1;
	list<int>::iterator cur = num.begin();
	while (num.size() > 1) {
		cur++;
		if (cur == num.end()) cur = num.begin(); //这里要在cur++下面,否则cur已经到end了(就应该跳到第0个位置),但后面却要把它删掉,结果找不到元素。
		i++;
		if (i%m == 0) {
			list<int>::iterator to_delete = cur;
			list<int>::iterator next = ++cur;
			if (next == num.end()) next = num.begin();
			num.erase(to_delete);
			cur = next;
			i = 1;
		}
	}
	cout << num.front();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值