LeetCode题解:Gray Code
来源:互联网 发布:淘宝运费险是卖家赔吗 编辑:程序博客网 时间:2024/05/04 07:00
Gray Code
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 - 001 - 111 - 310 - 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.
思路:
初次看到的时候觉得可能是要做图搜索的样子。但是事实上并不那么复杂,只要找到下一个未访问过的数就可以了。这里用一个简单的异或操作就可以flip一个位:x ^= (1 << bit)。另外用了一个set来保存已经访问过的数字。set一般是通过hash的方法来搜索的,因此平均花费的时间是O(1)。而map的key搜索则要O(log n),因为map的实现通常是基于红黑树的。
题解:
class Solution {public: vector<int> grayCode(int n) { vector<int> ret; set<int> usedval; auto flip = [&](int k, int bit) -> int { return k ^ (1 << bit); }; queue<int> visit; visit.push(0); while(!visit.empty()) { auto front = visit.front(); visit.pop(); ret.push_back(front); usedval.insert(front); // now check possible choices // we have to avoid the sgn bit for(int i = 0; i < n; ++i) { int newval = flip(front, i); if (usedval.find(newval) != usedval.end()) continue; else { visit.push(newval); break; } } } return ret; }};
- LeetCode题解:Gray Code
- leetcode题解-89. Gray Code
- LeetCode 题解(158): Gray Code
- 89. Gray Code 题解
- 题解:Gray Code
- LeetCode: Gray Code
- [LeetCode] 格雷码(Gray Code)
- LeetCode Gray Code
- [Leetcode] Gray Code
- [LeetCode] Gray Code
- leetcode 112: Gray Code
- LeetCode Gray Code
- [leetCode] Gray Code
- [LeetCode]Gray Code
- Leetcode: Gray Code
- [leetcode]Gray Code
- LeetCode-Gray Code
- [leetcode] Gray Code
- socket相关知识
- Longest Consecutive Sequence 从无序数组中找最长的连续数字 @LeetCode
- LeetCode题解:Binary Tree Postorder Traversal
- LeetCode题解:Convert Sorted Array to Binary Search Tree
- Windows与linux双系统安装
- LeetCode题解:Gray Code
- 我的Android进阶之旅------>关于调用Webservice查询火车票时刻表的几个接口介绍
- [Leetcode 56, Hard] Merge intervals
- Search for a Range 有序数组里查找一个数的出现区间 @LeetCode
- Subsets II 求有重复元素的集合的子集 @LeetCode
- LeetCode题解:Minimum Path Sum
- javabean数据库连接池(tomcat上配置)
- #android#基于ubuntu12.04开发环境的搭建
- Nachos _ multi _ programming