zoukankan      html  css  js  c++  java
  • 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);
        }
    
    }
    

      

  • 相关阅读:
    duilib listUI滚动列表的时候回出现在LIst外面显示的情况
    VS中关于字节大小的总结
    linux系统上搭建egret构建环境(针对5.3.x 版以上)
    android studio 2.0 Gradle HttpProxy 设置
    低压差稳压器--AMS1117芯片简介
    车联网技术简介
    MATLAB语音信号处理
    汇编语言系列Ⅳ 实现发出各种声音
    汇编语言系列Ⅲ 实现字符串操作
    汇编语言系列Ⅱ 实现简单数学运算
  • 原文地址:https://www.cnblogs.com/apanda009/p/7790627.html
Copyright © 2011-2022 走看看