圆圈中最后剩下的数

来源:互联网 发布:java web是做什么的 编辑:程序博客网 时间:2024/06/07 06:52

题目描述:0,1,…,n-1这n个数字排成一个圆圈,从数字0开始每次从这个圆圈里删除第m个数字。求出这个圆圈里城下的最后一个数字。

举例如下图所示:
这里写图片描述

书上提供了两种解法,第一种常规地用环形链表模拟圆圈,循环删除返回剩下的最后一个。第二种根据数学分析推导递归公式,计算得数。然鹅。。比较好的第二种方法好像不太懂呢

模拟圆圈的思路:用list构造链表,用迭代器扫描,当扫描到链表尾部时,移到头部,实现环形链表。

代码:

class Solution {public:    int LastRemaining_Solution(int n, int m)    {        if (n < 1 || m < 1)        return -1;        list<int> numbers;        for (int i = 0; i < n; i++) {            numbers.push_back(i);        }        list<int>::iterator current = numbers.begin();        while (numbers.size() > 1) {            //下面循环从i=1开始,因为要实现循环m-1次            for (int i = 1; i < m; i++) {                current++;                //实现把链表连成环                if (current == numbers.end())                    current = numbers.begin();            }            //这里要用到++current赋给next是因为迭代器不允许+1操作,只能自加,后面再自减回来            list<int>::iterator next = ++current;            if (next == numbers.end())                next = numbers.begin();            --current;            numbers.erase(current);            current = next;        }        return (*current);    }};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
(function () {('pre.prettyprint code').each(function () { var lines = (this).text().split(\n).length;varnumbering = $('
    ').addClass('pre-numbering').hide(); (this).addClass(hasnumbering).parent().append(numbering); for (i = 1; i
    原创粉丝点击