本文主要是介绍JZ46孩子们的游戏、约瑟夫环,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:https://www.nowcoder.com/practice/f78a359491e64a50bce2d89cff857eb6?tpId=13&tqId=11198&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking
下面是我的代码,效率比较低,看别人的答案,总结自己的经验。
public class Solution {public int LastRemaining_Solution(int n, int m) {if(n==0) return -1;int left=n,current=0,count=0,size=m;int arr[]=new int[n];while(left>1){if(arr[current]==0){if((count+1)%m==0){arr[current]=1;left--;}current=(current+1)%n;count=(count+1)%m;}else{current=(current+1)%n;}}int i=0;while(i<n){if(arr[i]==0)break;i++;}return i;}
}
归根结底是一个约瑟夫环问题,看下面这一篇就够了。
https://zhuanlan.zhihu.com/p/121159246
这篇关于JZ46孩子们的游戏、约瑟夫环的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!