FTPrep, 89 Gray Code
来源:互联网 发布:如何成为淘宝超级会员 编辑:程序博客网 时间:2024/06/06 03:56
这道题 其实很算法的关系不大,更重要的是找到格雷码的形成规律。
规律入下:
1,base case:0,1
2,f: g(x) --> g(x+1), 相当于把g(x)里的元素逆序遍历,同时加上 1<<(x),就得到了list中要添加的数。
1&2就说明了list的形成过程了。每一次+1有一个for,每一个for里要对之前的list进行遍历,又多了一个for,两个for搞定。
代码如下:
class Solution { public List<Integer> grayCode(int n) { List<Integer> result = new ArrayList<Integer>(); if(n<0) return result; if(n==0){ result.add(0); return result; } if(n==1){ result.add(0); result.add(1); return result; } result.add(0); result.add(1); // the following adding is based on the existing numbers, so need to add the basis, for populating!! for(int bitNum=2; bitNum<=n; bitNum++){ int last= result.size()-1; // every iteration, the result gets double in size, need to get the fixed index // since the size is growing when adding new elems. int numForBit= 1<<(bitNum-1); for(int index=last; index>=0; index--){ // populate from the existing base, BACKWARD!! result.add(result.get(index)+numForBit); // since 1 is already the 1st bit, so need to move (bitNum-1) } } return result; }}
阅读全文
0 0
- FTPrep, 89 Gray Code
- [leetcode 89] Gray Code
- LeetCode 89 Gray Code
- leetcode || 89、Gray Code
- Leetcode 89 Gray Code
- [leetcode] #89 Gray Code
- leetcode 89:Gray Code
- Leetcode #89 Gray Code
- LeetCode(89) Gray Code
- leetcode 89: Gray Code
- leetcode #89 Gray Code
- [89]Gray Code
- 【leetcode】【89】Gray Code
- 89Gray Code
- leetcode 89:Gray Code
- 89-m-Gray Code
- leetcode 89 Gray Code
- LeetCode 89 Gray Code
- [cnblogs镜像]Unity 点击屏幕发射射线 代码
- [cnblogs镜像]Unity 三维软件单位导入资源单位比例
- subline text添加python虚拟环境为编译工具
- Jenkins 关闭和重启详细介绍及实现
- [cnblogs镜像]Unity 设置2台摄像机的叠加
- FTPrep, 89 Gray Code
- 如果你恨他,就让他去做AWS云计算吧
- [cnblogs镜像]Unity设置Turorials-Wide布局
- [cnblogs镜像]Unity 声音播放不受Time.scale为0的影响
- [PTA] 线性结构1 两个有序链表序列的合并(15 分)
- [cnblogs镜像]NGUI 使用Grid自动排列UI
- [cnblogs镜像]Unity 手机屏幕翻转问题 横屏
- [cnblogs镜像]Unity 退出游戏 方法
- 玲珑oj 1158