当前位置:网站首页>【日常训练--腾讯精选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));
}
}
边栏推荐
- Binary search
- Introduction to TS, constructor and its this, inheritance, abstract class and interface
- 如何让化工企业的ERP库存账目更准确
- Mode - "Richter replacement principle"
- AITM2-0002 12s或60s垂直燃烧试验
- Viewrootimpl and windowmanagerservice notes
- LeetCode: Distinct Subsequences [115]
- sql系列(基础)-第二章 限制和排序数据
- haas506 2.0开发教程 - 阿里云ota - pac 固件升级(仅支持2.2以上版本)
- 驱动壳美国测试UL 2043 符合要求有哪些?
猜你喜欢

R语言【数据管理】

【案例】元素的显示与隐藏的运用--元素遮罩

Abnova CRISPR spcas9 polyclonal antibody protocol

XML modeling

显示器要申请BS 476-7 怎么送样?跟显示屏一样吗??

如何让化工企业的ERP库存账目更准确

显示屏DIN 4102-1 Class B1防火测试要求

Open source SPL eliminates tens of thousands of database intermediate tables

木板ISO 5660-1 热量释放速率摸底测试
![[case] Application of positioning - Taobao rotation map](/img/2d/c834ce95a2c8e53a20e67fa2e99439.png)
[case] Application of positioning - Taobao rotation map
随机推荐
《SAS编程和数据挖掘商业案例》学习笔记# 19
Implementation of redis unique ID generator
概率论机器学习的先验知识(上)
ts 之 泛型
sql系列(基础)-第二章 限制和排序数据
Is Kai Niu 2980 useful? Is it safe to open an account
PHP反序列化+MD5碰撞
EN 438-7建筑覆盖物装饰用层压板材产品—CE认证
poj 3414 Pots (bfs+线索)
The transformation based on vertx web sstore redis to realize the distributed session of vertx HTTP application
Abnova CD81 monoclonal antibody related parameters and Applications
学习机器人无从下手?带你体会当下机器人热门研究方向有哪些
SQL series (basic) - Chapter 2 limiting and sorting data
Aitm 2-0003 horizontal combustion test
How to make ERP inventory accounts of chemical enterprises more accurate
Sequence alignment
AITM2-0002 12s或60s垂直燃烧试验
Open source SPL eliminates tens of thousands of database intermediate tables
启牛2980有没有用?开户安全吗、
【案例】元素的显示与隐藏的运用--元素遮罩