题目描述
每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0…m-1报数…这样下去…直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!_)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)
如果没有小朋友,请返回-1
思路一: 这是约瑟夫环问题。建立一个环形链表,模拟题目中的报数过程,直到最后剩下一个结点。
C++
class Solution {
public:
//建立链表
struct ListNode {
int val;
struct ListNode *next;
ListNode (int x) :
val(x), next(NULL) {
};
};
int LastRemaining_Solution(int n, int m)
{
if (n == 0 || m == 0) return -1;
if (n == 1) return 0;
ListNode *root = new ListNode(0); //先建立一个根节点
ListNode *p = root; //用来遍历一个环
//开始建立环
ListNode *temp; //用于后面删除节点的
//0值的已经建立过了,要建立1~(n-1)的
for (int i = 1; i < n; i++)
{
ListNode *q = new ListNode(i);
p -> next = q;
q -> next = root;
p = p -> next;
}
p -> next = root; //形成一个环
int countn = n;
p = root;
while (countn > 1)
{
int countm = 1;
//定位到要删除结点的前一个结点
while (countm < m - 1)
{
p = p -> next;
countm++;
}
temp = p -> next; //要删除的结点
p -> next = temp -> next;
delete temp;
countn--;
p = p -> next; //从删除结点的下一个结点开始重新报数
}
int res = p -> val;
return res;
}
};
思路二: 模拟游戏过程推出数学公式解如下,其中 i 为当前列表的下标,初始化为0。
i = (i + m - 1) % list.size()
举例: 比如 n = 5,m = 2。list 为 [0, 1, 2, 3, 4]
- 第一次列表去除1,list 变为 [0, 2, 3, 4],去除数字的下标 i = 1 = (0 + 2 - 1) % 5
- 第二次列表去除3,list 变为[0, 2, 4],去除数字的下标 i = 2 = (1 + 2 - 1) % 4
- 第三次列表去除0,list 变为[2, 4],去除数字的下标 i = 0 = (2 + 2 - 1) % 3
- 第四次列表去除4,list 变为[2],去除数字的下标 i = 1 = (0 + 2 - 1) % 2
C++
class Solution {
public:
int LastRemaining_Solution(int n, int m)
{
if (n == 0 || m == 0) return -1;
if (n == 1) return 0;
vector<int>temp;
for (int i = 0; i < n; i++)
temp.push_back(i);
int i = 0;
while (temp.size() > 1)
{
i = (i + m - 1) % temp.size();
temp.erase(temp.begin() + i); //删除当前列表的第i个元素
}
return temp.size() == 1 ? temp[0] : -1;
}
};
Python
# -*- coding:utf-8 -*-
class Solution:
def LastRemaining_Solution(self, n, m):
# write code here
if not m or not n:
return -1
res = range(n)
i = 0
while len(res) > 1:
i = (i + m - 1) % len(res)
res.pop(i)
return res[0]
267

被折叠的 条评论
为什么被折叠?



