环形链表中最后剩下的数字
list
题目:0,1,...,n-1这n个数字排成一个圆圈,从数字0开始每次从这个圆圈里删除第n个数字。求出这个圆圈里剩下的最后一个数字。
思路:可以用list来模拟环形链表,当迭代器达到end时(end是超出末尾的哨兵),迭代器重新赋值为begin。list内部erase效率非常高,注意erase的迭代器的后一位是作为下一次迭代的开始位,也要满足环形特点。时间复杂度为O(mn),空间复杂度为O(n)。
LastRemaining
1 int LastRemaining(unsigned int n, unsigned int m) 2 { 3 if(n < 1 || m < 1) 4 return -1; 5 6 unsigned int i = 0; 7 8 list<int> numbers; 9 for(i = 0; i < n; ++ i) 10 numbers.push_back(i); 11 12 list<int>::iterator current = numbers.begin(); 13 while(numbers.size() > 1) 14 { 15 for(int i = 1; i < m; ++ i) 16 { 17 current ++; 18 if(current == numbers.end()) 19 current = numbers.begin(); 20 } 21 22 list<int>::iterator next = ++ current; 23 if(next == numbers.end()) 24 next = numbers.begin(); 25 26 -- current; 27 numbers.erase(current); 28 current = next; 29 } 30 31 return *(current); 32 }