题目:
0, 1, …, n-1这n个数字排成一个圆圈,从数字0开始每次从这个圆圈里删除第m个数字,求出这个圆圈里面剩下的最后一个数字。
代码实现:
int GetLastRemainData(int n, int m)
{
if (n < 2 || m < 1) return -1;
std::list<int> datas;
for (int curData = 0; curData <= n; ++curData) datas.push_back(curData);
while ((int)datas.size() != 1)
{
// 取得位置为m的元素
auto curIter = datas.begin();
for (int idx = 1; idx < m; ++idx)
{
++curIter;
if (curIter == datas.end()) curIter = datas.begin();
}
// 取得m元素的下一个位置
auto nextIter = ++curIter; // 因为std::list为双线迭代器,不能使用nextIter = curIter + 1;
if (nextIter == datas.end()) nextIter = datas.begin();
--curIter; // 还原
// 删除当前元素,重新赋值
datas.erase(curIter);
curIter = nextIter;
}
return datas.front();
}