剑指offer——面试题34:丑数
2018-03-24 16:28
453 查看
剑指offer——面试题34:丑数
Solution1:自己想的垃圾思路因为超时GG了。。。
class Solution { public: int GetUglyNumber_Solution(int index) { //输出第index个丑数 int count = 1; if(index == 1) return count; for(int i = 2; ; i++){ if(isUglyNum(i) == true){ count++; if(count == index) return i; } } } bool isUglyNum(int n){ while(n > 1) { for(int i = 2; i <= n; i++){ if(n%i == 0){ //如果n能被i整除,i是因子,对i分小于等于5和大于5两种情况讨论 if(i <= 5) { n /= i; break; } if(i > 5) return false; } } } return true; } };
Solution2:
答案参考网址:
[1]http://www.cnblogs.com/qqky/p/6964764.html
[2]https://www.nowcoder.com/profile/5810633/codeBookDetail?submissionId=16629921
解题思路:https://blog.csdn.net/lhanchao/article/details/52079323
本题定义三个变量,对于当前已排好序找到的最大的丑数M,记录恰乘2、乘3、乘5大于当前最大的丑数M的三个位置,然后求三个位置*2 *3 *5的最小值即为下一个丑数的值
class Solution { public: int GetUglyNumber_Solution(int index) { if (index < 7)return index; vector<int> res(index); res[0] = 1; int t2 = 0, t3 = 0, t5 = 0, i; for (i = 1; i < index; ++i) { res[i] = min(res[t2] * 2, min(res[t3] * 3, res[t5] * 5)); if (res[i] == res[t2] * 2)t2++; if (res[i] == res[t3] * 3)t3++; if (res[i] == res[t5] * 5)t5++; } return res[index - 1]; } };
再感慨一句,别人的思路真牛逼啊~
相关文章推荐
- 剑指offer——面试题34:丑数
- 剑指Offer----面试题34:丑数
- 【剑指Offer学习】【面试题34:丑数】
- 剑指Offer面试题34题:丑数(Ugly Number)(while循环里面的三个小问题)
- 剑指offer--面试题34: 丑数
- 剑指offer——面试题34:丑数
- 【剑指Offer学习】【面试题34:丑数】
- 剑指offer-面试题34:丑数
- 【剑指Offer】面试题34:丑数
- 剑指Offer面试题34:丑数 Java实现
- 剑指Offer_面试题34_丑数
- 剑指Offer:面试题34——丑数(java实现)
- 剑指offer 面试题34 丑数
- 【剑指offer 面试题34】丑数
- 剑指offer 面试题34 丑数
- [剑指offer][面试题34]丑数
- 剑指offer面试题[34]丑数
- 剑指offer之面试题34丑数
- 剑指offer-面试题34-丑数
- 【剑指offer】5.3时间效率与空间效率的平衡——面试题34:丑数