前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
For example, given n = 2, return [0,1,3,2]
. Its gray code sequence is:
00 - 0 01 - 1 11 - 3 10 - 2
Note:
For a given n, a gray code sequence is not uniquely defined.
For example, [0,2,3,1]
is also a valid gray code sequence according to the above definition.
For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.
这个题目想了半天,单纯从题意要递归出来不现实。。。看了论坛,不得不服,观察能力巨强。。真心觉得要对数字很敏感才行。。 Your runtime beats 52.40% of java submissions.public class Solution {
public ArrayList<Integer> grayCode(int n) {
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(0);
for(int i=0;i<n;i++){
int inc = 1<<i;
for(int j=arr.size()-1;j>=0;j--){
arr.add(arr.get(j)+inc);
}
}
return arr;
}
}