链接:
https://leetcode.com/problems/gray-code/
大意:
给定一个非负整数n,要求写出所有二进制位数为n的数,且相邻的两数的二进制表达式只有一位不同。另:当n==0时,只存在0这一个数。例子:
思路:
通过观察规律可知:
n == 0时,list中可含元素:0
n == 1时,list中可含元素:0,1
n == 2时,list中可含元素:0,1,3,2
n == 3时,list中可含元素:0,1,3,2,6,7,5,4
....
可以看到,n == i + 1时的list中的元素中:前半部分为n == i时list中的元素,后半部分为 n == i的list的逆序遍历元素加上某一个数,可以看到这个数是2^(n - 1)。
其实,以上这些规律是可以通过写出各个数的二进制表达形式可以得到的。
代码:
class Solution {
public List<Integer> grayCode(int n) {
ArrayList<Integer> res = new ArrayList<>();
res.add(0);
int i = 0, gap = 1;
while (i < n) {
int index = res.size() - 1;
while (index >= 0) {
res.add(res.get(index--) + gap);
}
gap <<= 1;
i++;
}
return res;
}
}
结果:
结论:
当需要访问List中的元素时,优先使用ArrayList。在尾部插入一个数据,ArrayList和LinkedList的时间复杂度都是O(1),不考虑找到尾部位置的时间开销的话。