圆圈中剩下的数字

https://www.nowcoder.com/practice/f78a359491e64a50bce2d89cff857eb6?tpId=13&tqId=11199&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

思路:建立一个环形链表模拟这个过程即可。可以用STL的list来模拟环形链表,在遍历到链表的尾部的时候记得把指针弄到链表头部就好了。

#include <iostream> 
#include <cstring>
#include<string>
#include <cstdio>
#include<queue>
#include<stack>
#include<list>
using namespace std;


class Solution {
public:
	list<int>L;
    int LastRemaining_Solution(int n, int m)
    {
		if(n < 1 || m < 1)
			return -1;

		for(int i = 0; i < n; i++)
			L.push_back (i);

		list<int>::iterator it = L.begin();

		while(L.size() > 1)//删除只保留一个数字
		{
			for(int i = 0; i < m - 1; i++)//找到从0开始数的第m个数字
			{
				it++;
				if(it == L.end() )//迭代器移动到尾部就把其放到链表头部
					it = L.begin();

			}
			it = L.erase(it);//删除第m个数字并返回迭代器的下一个元素
			if(it == L.end() )//再次检测是否到尾部
				it = L.begin();
		}
		return L.front();//剩下的最后一个元素肯定就是头部了
        
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值