标签:
题目是遇到偶数/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
一个数一个数慢慢算,如下算法求出每个数的cycle length
1 package Sorting; 2 import java.util.*; 3 4 public class Solution2 { 5 public List<Integer> maxCycleLen(int min, int max) { 6 List<Integer> maxCycle = new ArrayList<Integer>(); 7 for (int i=min; i<=max; i++) { 8 helper(maxCycle, i); 9 } 10 return maxCycle; 11 } 12 13 public void helper(List<Integer> maxCycle, int num) { 14 int len = 1; 15 while (num != 1) { 16 if (num%2 == 1) num = num*3+1; 17 else num = num/2; 18 len++; 19 } 20 maxCycle.add(len); 21 } 22 23 /** 24 * @param args 25 */ 26 public static void main(String[] args) { 27 // TODO Auto-generated method stub 28 Solution2 sol = new Solution2(); 29 List<Integer> res = sol.maxCycleLen(1, 100000); 30 System.out.println(res); 31 } 32 33 }
follow up: 建立一个Lookup table, 算过的数就不算了
1 package Sorting; 2 import java.util.*; 3 4 public class Solution3 { 5 HashMap<Integer, Integer> map; 6 public List<Integer> maxCycleLen(int min, int max) { 7 List<Integer> maxCycle = new ArrayList<Integer>(); 8 map = new HashMap<Integer, Integer>(); 9 for (int i=min; i<=max; i++) { 10 helper(maxCycle, i); 11 } 12 return maxCycle; 13 } 14 15 public void helper(List<Integer> maxCycle, int num) { 16 int len = 1; 17 int numcopy = num; 18 while (num != 1) { 19 if (map.containsKey(num)) { 20 len += map.get(num)-1; 21 break; 22 } 23 if (num%2 == 1) num = num*3+1; 24 else num = num/2; 25 len++; 26 } 27 maxCycle.add(len); 28 map.put(numcopy, len); 29 } 30 31 /** 32 * @param args 33 */ 34 public static void main(String[] args) { 35 // TODO Auto-generated method stub 36 Solution3 sol = new Solution3(); 37 List<Integer> res = sol.maxCycleLen(1, 100000); 38 System.out.println(res); 39 } 40 41 }
或者
1 public void helper(List<Integer> maxCycle, int num) { 2 int len = 0; 3 int numcopy = num; 4 while (!map.containsKey(num)) { 5 if (num == 1) { 6 map.put(1, 1); 7 maxCycle.add(1); 8 return; 9 } 10 if (num%2 == 1) num = num*3+1; 11 else num = num/2; 12 len++; 13 } 14 len = len + map.get(num); 15 maxCycle.add(len); 16 map.put(numcopy, len); 17 }
Groupon面经Prepare: Max Cycle Length
标签:
原文地址:http://www.cnblogs.com/EdwardLiu/p/5180876.html