解法一 环形链表
使用链表构造一个环,每个删除第m个数直到链表中剩下一个元素
class Solution {
public int lastRemaining(int n, int m) {
if (n < 1 || m < 1)
return -1;
LinkedList<Integer> numbers = new LinkedList<>();
for (int i = 0; i < n; ++i)
numbers.offer(i);
ListIterator<Integer> current = numbers.listIterator(0);
while (numbers.size() > 1) {
for (int i = 1; i < m; ++i) {
current.next();
if (!current.hasNext())
current = numbers.listIterator(0);
}
current.next();
current.remove();
if (!current.hasNext())
current = numbers.listIterator(0);
}
return current.next();
}
}
解法二 数学
class Solution {
public int lastRemaining(int n, int m) {
if (n < 1 || m < 1) return -1;
int last = 0;
for (int i = 2; i <=n; i++) {
last = (last + m) % i;
}
return last;
}
}