标签:
题目描述:public int NthUglyNumber(int n) { var hash = new Dictionary<int, int>(); hash.Add(1 , 1); hash.Add(2 , 2); hash.Add(3 , 3); hash.Add(4 , 4); hash.Add(5 , 5); if(hash.ContainsKey(n)){ return hash[n]; } var count = 5; var n1 = 6; while(count < n){ if(n1 % 2 == 0 && hash.ContainsKey(n1/2) || n1 % 3 == 0 && hash.ContainsKey(n1/3) || n1 % 5 == 0 && hash.ContainsKey(n1/5)){ hash.Add(n1, count); count ++; } n1++; } return hash.Keys.Last(); }
public class Solution { public int NthUglyNumber(int n) { var i2 = 1; var i3 = 1; var i5 = 1; var uglies = new List<int>(); uglies.Add(1); while (uglies.Count < n) { var v2 = uglies[i2-1] * 2; var v3 = uglies[i3-1] * 3; var v5 = uglies[i5-1] * 5; int min = Math.Min(v2, Math.Min(v3, v5)); if (min == v2) { i2++; } if (min == v3){ i3++; } if (min == v5) { i5++; } uglies.Add(min); } return uglies.Last(); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/lan_liang/article/details/49885465