题解 | #孩子们的游戏(圆圈中最后剩下的数)#
孩子们的游戏(圆圈中最后剩下的数)
http://www.nowcoder.com/practice/f78a359491e64a50bce2d89cff857eb6
import java.util.*;
public class Solution{
public int LastRemaining_Solution(int n, int m) {
//环状列表
List<ListNode> nodes = new ArrayList<>();
for(int i = 0 ; i < n; i++){
ListNode node = new ListNode(i);
nodes.add(node);
}
for(int i = 0 ; i < n; i++){
if(i < n - 1){
nodes.get(i).next = nodes.get(i+1);
}else{
nodes.get(i).next = nodes.get(0);
}
}
ListNode pHead = nodes.get(0);
int j = 0;
while(pHead.next != pHead){
if(j == (m - 2)){
//在环状链表中去除该节点的下一个节点
pHead.next = pHead.next.next;
j = 0;
pHead = pHead.next;
}else{
pHead = pHead.next;
j++;
}
}
return pHead.val;
}
}