package JianZhioffer; import java.util.ArrayList; import java.util.List; public class test62 { public static void main(String[] args) { int n=5; int m=2; System.out.println(lastRemaining(n, m)); } //最后一个元素时候删除得是第0个,假设n-1元素删除第x个,那么n元素删除(m+x)%n public static int lastRemaining(int n, int m) { return f(n, m); } public static int f(int n, int m) { if (n == 1) { return 0; } int x = f(n - 1, m); return (m + x) % n; } //超时 public static int lastRemaining1(int n, int m) { if(n==1){ return 0; } if(m==1){ return n-1; } ListNode list=new ListNode(0); ListNode x=list; for(int i=1;i<n;i++){ list.next=new ListNode(i); list=list.next; } list.next=x; ListNode list1=x; while(list1.next!=list1){ int l=1; int k=1; ListNode list2=list1; while(k<m-1){ list2=list2.next; k++; } ListNode list4=list2.next.next; // ListNode list2=list1.next; list2.next=list4; list1=list4; // list4.next=list1; } return list1.val; } }