From 9d31289601505a8f897fc0129d67a6b75bd91acb Mon Sep 17 00:00:00 2001 From: ShusenTang Date: Wed, 24 Jun 2020 20:19:06 +0800 Subject: [PATCH] update solution 3 --- solutions/89. Gray Code.md | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/solutions/89. Gray Code.md b/solutions/89. Gray Code.md index d1b89f7..0e79381 100644 --- a/solutions/89. Gray Code.md +++ b/solutions/89. Gray Code.md @@ -21,9 +21,9 @@ Int Grey Code Binary 参考维基百科及[这篇博客](http://www.omegaxyz.com/2017/11/16/grayandbi/)可很容易地写出代码。 ## 思路三(最快) -参考[维基百科](https://zh.wikipedia.org/wiki/%E6%A0%BC%E9%9B%B7%E7%A0%81#%E9%8F%A1%E5%B0%84%E6%8E%92%E5%88%97)我们知道,格雷码是按照镜面排列的,n位元的格雷码可以从n-1位元的格雷码以上下镜射后加上新位元的方式快速的得到,如下图所示。 +参考[维基百科](https://zh.wikipedia.org/wiki/%E6%A0%BC%E9%9B%B7%E7%A0%81#%E9%8F%A1%E5%B0%84%E6%8E%92%E5%88%97)我们知道,**格雷码是按照镜面排列的**,n位元的格雷码可以从n-1位元的格雷码以上下镜射后加上新位元的方式快速的得到,如下图所示。 ![graycode](http://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Binary-reflected_Gray_code_construction.svg/250px-Binary-reflected_Gray_code_construction.svg.png) -这样就可以用迭代的方式产生格雷码。 +可以在前面加上新位元(如上图绿色所示),这样就和思路二产生的一样了;也可以在后面添加新位元,也是满足要求的(相邻两个编码只有一个bit不同)。 @@ -76,16 +76,20 @@ public: class Solution { public: vector grayCode(int n) { - vectorres; - res.push_back(0); - for(int i = 0; i < n; i++){ - int size = res.size(); - for(int j = 0; j < size; j++) - res.push_back(res[size - j - 1]); - for(int j = 0; j < res.size(); j++){ - res[j] = res[j] | ((j / size) << i); // 在左边添加一半的0和一半的1 - // res[j] = (res[j] << 1) | (j / size); // 在右边添加一半的0和一半的1 - } + vectorres{0}; + for(int b = 0; b < n; b++){ + for(int i = res.size() - 1; i >= 0; i--) // 镜面复制 + res.push_back(res[i]); + + int half_size = res.size() >> 1; + for(int i = 0; i < half_size; i++){ + // 在前面添加新位元 + res[i + half_size] += (1 << b); + + // 在后面添加新位元 + // res[i] <<= 1; + // res[i + half_size] = (res[i + half_size] << 1) + 1; + } } return res; }