当前位置:网站首页>【日常训练--腾讯精选50】89. 格雷编码(看题解才会的)
【日常训练--腾讯精选50】89. 格雷编码(看题解才会的)
2022-07-05 21:03:00 【Puppet__】
题目
n 位格雷码序列 是一个由 2n 个整数组成的序列,其中:
每个整数都在范围 [0, 2n - 1] 内(含 0 和 2n - 1)
第一个整数是 0
一个整数在序列中出现 不超过一次
每对 相邻 整数的二进制表示 恰好一位不同 ,且
第一个 和 最后一个 整数的二进制表示 恰好一位不同
给你一个整数 n ,返回任一有效的 n 位格雷码序列 。
示例 1:
输入:n = 2
输出:[0,1,3,2]
解释:
[0,1,3,2] 的二进制表示是 [00,01,11,10] 。
- 00 和 01 有一位不同
- 01 和 11 有一位不同
- 11 和 10 有一位不同
- 10 和 00 有一位不同
[0,2,3,1] 也是一个有效的格雷码序列,其二进制表示是 [00,10,11,01] 。 - 00 和 10 有一位不同
- 10 和 11 有一位不同
- 11 和 01 有一位不同
- 01 和 00 有一位不同
示例 2:
输入:n = 1
输出:[0,1]
提示:
1 <= n <= 16
代码
package tencent50;
import java.util.ArrayList;
import java.util.List;
public class leetcode89 {
// 感觉是背答案的题...
// 关键是弄清楚格雷编码的生成过程格雷编码的生成过程 G(i) = i ^ (i / 2)
public List<Integer> grayCode(int n) {
List<Integer> ansList = new ArrayList<>();
// 区间是[0,2^n)
for (int i = 0; i < 1<<n; i++){
ansList.add(i ^ i>>1);
}
return ansList;
}
public static void main(String[] args) {
leetcode89 obj = new leetcode89();
System.out.println(obj.grayCode(2));
}
}
边栏推荐
- wpf 获取datagrid 中指定行列的DataGridTemplateColumn中的控件
- LeetCode_ Hash table_ Difficulties_ 149. Maximum number of points on the line
- Norgen AAV extractant box instructions (including features)
- Abnova maxpab mouse derived polyclonal antibody solution
- Duchefa p1001 plant agar Chinese and English instructions
- ViewRootImpl和WindowManagerService笔记
- Abnova cyclosporin a monoclonal antibody and its research tools
- 珍爱网微服务底层框架演进从开源组件封装到自研
- systemd-resolved 开启 debug 日志
- poj 3414 Pots (bfs+线索)
猜你喜欢

Using webassembly to operate excel on the browser side

教你自己训练的pytorch模型转caffe(二)
![最长摆动序列[贪心练习]](/img/e1/70dc21b924232c7e5e3da023a4bed2.png)
最长摆动序列[贪心练习]

Mathematical analysis_ Notes_ Chapter 9: curve integral and surface integral

Talk about my fate with some programming languages

PHP反序列化+MD5碰撞

浅聊我和一些编程语言的缘分

10000+ 代码库、3000+ 研发人员大型保险集团的研发效能提升实践

ArcGIS栅格重采样方法介绍

Duchefa cytokinin dihydrozeatin (DHZ) instructions
随机推荐
示波器探头对测量带宽的影响
Material Design组件 - 使用BottomSheet展现扩展内容(二)
从架构上详解技术(SLB,Redis,Mysql,Kafka,Clickhouse)的各类热点问题
LeetCode: Distinct Subsequences [115]
Comparison table of foreign lead American abbreviations
教你自己训练的pytorch模型转caffe(二)
Is it necessary for bazel to learn
Monorepo management methodology and dependency security
Duchefa low melting point agarose PPC Chinese and English instructions
判断横竖屏的最佳实现
The reason why the ncnn converted model on raspberry pie 4B always crashes when called
When steam education enters personalized information technology courses
Open source SPL eliminates tens of thousands of database intermediate tables
CLion配置visual studio(msvc)和JOM多核编译
浅聊我和一些编程语言的缘分
基于flask写一个接口
poj 3414 Pots (bfs+线索)
Phpstudy Xiaopi's MySQL Click to start and quickly flash back. It has been solved
js常用方法封装
Pytoch practice -- MNIST dataset handwritten digit recognition