美文网首页
Leetcode 89. Gray Code

Leetcode 89. Gray Code

作者: persistent100 | 来源:发表于2017-11-30 21:44 被阅读0次

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.

分析

灰码序列,就是二进制形式的各位只有一个相反。我是用的方法是,从0开始,依次翻转一个位,如果新数字未出现过,就加到结果数组中。然后对该数进一步翻转其中的一个位。该方法循环次数较多,比较慢。
网上有其他方法,找到了该规律: G(i) = i^ (i/2).可以使用。

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* grayCode(int n, int* returnSize) {
    int *ans=(int*)malloc(sizeof(int)*1000000);
    ans[0]=0;
    *returnSize=1;
    int max=1;
    
    for(int i=0;i<n;i++)
        max=max*2;
    for(int i=1;i<max;i++)
    {
        for(int j=0;j<n;j++)
        {
            int temp=ans[*returnSize-1]^(1<<j);
            int k=0;
            for(k=0;k<*returnSize;k++)
            {
                if(ans[k]==temp)break;
            }
            if(k<*returnSize)
                continue;
            else
            {
                ans[*returnSize]=temp;
                *returnSize=*returnSize+1;
                break;
            }
        }
    }
    return ans;
}

相关文章

  • Leetcode 89. Gray Code

    文章作者:Tyan博客:noahsnail.com | CSDN | 简书 1. Description 2. S...

  • Leetcode 89. Gray Code

    The gray code is a binary numeral system where two succes...

  • LeetCode89 Gray Code

    LeetCode89 Gray Code The gray code is a binary numeral sy...

  • LeetCode笔记:89. Gray Code

    问题: The gray code is a binary numeral system where two su...

  • [Math]89. Gray Code

    分类:Math 时间复杂度: O(n) 空间复杂度: O(n) 89. Gray Code The gray co...

  • 89. Gray Code

    这题做的很虚, 嗯,居然过了 题目中的一种做法的复现: 打死我吧,打死我我可能会想出来这种办法

  • 89. Gray Code

    题目描述:给非负整数 n 表示二进制位数,输出所有的 n 位格雷码,以0开始。 分析:时间复杂度O(2^n),空间...

  • 89. Gray Code

  • 89. Gray Code

    i = i^(i/2) 别问我咋的出来的, 不知道。。。

  • 89. Gray Code

    The gray code is a binary numeral system where two succes...

网友评论

      本文标题:Leetcode 89. Gray Code

      本文链接:https://www.haomeiwen.com/subject/krmbbxtx.html