zoukankan      html  css  js  c++  java
  • java解答:有17个人围成一圈(编号0~16),从第0号的人开始从1报数,凡报到3的倍数的人离开圈子,然后再数下去,直到最后只剩下一个人为止,问此人原来的位置是多少号?

    package ttt;
    
    import java.util.HashMap;
    import java.util.Map.Entry;
    
    /**
     * 有17个人围成一圈(编号0~16),从第0号的人开始从1报数,凡报到3的倍数的人离开圈子,然后再数下去,
     * 直到最后只剩下一个人为止,问此人原来的位置是多少号?
     *
     */
    public class n人报数m时离开 {
    
        public static void main(String[] args) {
            HashMap<Integer, Integer> theQuee = new HashMap<Integer,Integer>();
            for (int i = 0; i < 17; i++) {
                theQuee.put(i, i+1);//编号,固定位置
            }
            HashMap<Integer, Integer> itretMap = itretMap(theQuee,theQuee.size());
            for (Entry<Integer,Integer> entry  : itretMap.entrySet()) {
                if(entry.getValue()!= 0){
                    System.out.println("结果:"+entry.getKey());
                }
            }
        }
    
        //遍历Map并给非3的倍数的Key的value+1
        public static HashMap<Integer, Integer> itretMap(HashMap<Integer,Integer> map,int lenth){
            int sum = 0;
            for (Entry<Integer,Integer> entry : map.entrySet()) {
                int value = entry.getValue();
                if(value%3 != 0){//不可以整除
                    entry.setValue(value+lenth);//
                    sum++;//进入下一轮
                }else{
                    if(0!=entry.getValue()){//避免重复淘汰
                        entry.setValue(0);//淘汰
                        lenth --;//参与者-1
                    }
                }
            }
            if(sum>1){//
                System.out.println("还要继续,还有:"+sum);
                return itretMap(map,sum);
            }else{//已决出胜出者
                return map;//返回map
            }
        }
    }

    加班回来的路上看到一个这样的题,题目就是标题,

    (原题地址:http://www.cnblogs.com/tonybinlj/archive/2009/01/04/1367856.html),然后自我感觉用了个比较拙劣的方式,最后还是实现了。这里的17和3当然可以当做参数m,n来处理。。
    弄完网上找了找。C系列实现形式思路基本上是一样的。
    然后数学好的三行代码就搞定了。。遍历次数也是最少的。效率达到O(n):
        public static void main(String[] args) {
            int n =0;
            for (int i = 2; i <= 17; i++) {
                n = (n+3)%i;
            }
            System.out.println(n);
        }
                
  • 相关阅读:
    手把手教你利用create-nuxt-app脚手架创建NuxtJS应用
    初识NuxtJS
    webpack打包Vue应用程序流程
    用选择器代替表格列的筛选功能
    Element-UI
    Spectral Bounds for Sparse PCA: Exact and Greedy Algorithms[贪婪算法选特征]
    Sparse Principal Component Analysis via Rotation and Truncation
    Generalized Power Method for Sparse Principal Component Analysis
    Sparse Principal Component Analysis via Regularized Low Rank Matrix Approximation(Adjusted Variance)
    Truncated Power Method for Sparse Eigenvalue Problems
  • 原文地址:https://www.cnblogs.com/MyOceansWeb/p/7745740.html
Copyright © 2011-2022 走看看