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); } }