• Groupon面经Prepare: Max Cycle Length


    题目是遇到偶数/2,遇到奇数 *3 + 1的题目,然后找一个range内所有数字的max cycle length。
    对于一个数字,比如说44,按照题目的公式不停计算,过程是 44, 22, 11, 8, 9 ,1(瞎起的),
    从44到1的这个sequence的长度,叫做cycle length。
    然后题目是给一个range,比如[2,300],求这里面所有数字的cycle length的最大值。follow up跑1到1 million

    package Sorting;
    import java.util.*;
    
    public class Solution2 {
        public List<Integer> maxCycleLen(int min, int max) {
            List<Integer> maxCycle = new ArrayList<Integer>();
            for (int i=min; i<=max; i++) {
                helper(maxCycle, i);
            }
            return maxCycle;
        }
        
        public void helper(List<Integer> maxCycle, int num) {
            int len = 1;
            while (num != 1) {
                if (num%2 == 1) num = num*3+1;
                else num = num/2;
                len++;
            }
            maxCycle.add(len);
        }
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Solution2 sol = new Solution2();
            List<Integer> res = sol.maxCycleLen(1, 100000);
            System.out.println(res);
        }
    
    }
    

      

    follow up: 建立一个Lookup table, 算过的数就不算了

    package Sorting;
    import java.util.*;
    
    public class Solution3 {
        HashMap<Integer, Integer> map;
        public List<Integer> maxCycleLen(int min, int max) {
            List<Integer> maxCycle = new ArrayList<Integer>();
            map = new HashMap<Integer, Integer>();
            for (int i=min; i<=max; i++) {
                helper(maxCycle, i);
            }
            return maxCycle;
        }
        
        public void helper(List<Integer> maxCycle, int num) {
            int len = 0;
            int numcopy = num;
            while (!map.containsKey(num)) {
                if (num == 1) {
                    map.put(1, 1);
                    maxCycle.add(1);
                    return;
                }
                if (num%2 == 1) num = num*3+1;
                else num = num/2;
                len++;
            }
            len = len + map.get(num);
            maxCycle.add(len);
            map.put(numcopy, len);
        }
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Solution3 sol = new Solution3();
            List<Integer> res = sol.maxCycleLen(1, 100000);
            System.out.println(res);
        }
    
    }
    

      

  • 相关阅读:
    牛客网暑期ACM多校训练营(第九场)D
    有向图欧拉回路个数 BEST定理
    BZOJ 4894 有向图 外向生成树个数
    HDU 3364 高斯消元
    HDU 6437 最(大) 小费用最大流
    高斯消元 模板
    无向图生成树计数 基尔霍夫矩阵 SPOJ Highways
    HDU 6397 组合数学+容斥 母函数
    第三章 数据表示法
    第二章 二进制数值和记数系统
  • 原文地址:https://www.cnblogs.com/apanda009/p/7790627.html
Copyright © 2020-2023  润新知