zoukankan      html  css  js  c++  java
  • LeetCode Gray Code

    原题链接在这里:https://leetcode.com/problems/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 - 0
    01 - 1
    11 - 3
    10 - 2

    题解:

    根据graycode的特性:在n增大1时,在原有list的末尾按照原有list的倒序每个数字首位digit加上一个1 加回到list中.

    n = 0时,[0]

    n = 1时,[0,1]

    n = 2时,[00,01,11,10] 原有[0,1], 按照倒序[1,0], 首位加1变成[11,10]加回到原有的[0,1]后面, 就变成[0, 1, 11, 10]了.

    n = 3时,[000,001,011,010,110,111,101,100]

    Time Complexity: O(2^n). Space: O(1).不考虑res.

    AC Java:

     1 public class Solution {
     2     public List<Integer> grayCode(int n) {
     3         List<Integer> res = new ArrayList<Integer>();
     4         if(n<0){
     5             return res;
     6         }
     7         //when n = 0, return [0]
     8         res.add(0);
     9         for(int i = 0; i<n; i++){
    10             int len = res.size();
    11             //addNum 是要加的首位1
    12             int addNum = 1<<i;
    13             for(int j = len-1; j>=0; j--){
    14                 res.add(addNum+res.get(j));
    15             }
    16         }
    17         return res;
    18     }
    19 }
  • 相关阅读:
    OC实现个人中心页面
    3D Touch开发技巧的笔记
    APP快速搭建框架
    Swift10大开源项目记录
    iOS进阶学习笔记
    如何使启动界面图片全屏
    【DRF框架】restfull规范
    【DRF框架】版本控制组件
    【DRF框架】路由组件
    【DRF框架】视图组件
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4908208.html
Copyright © 2011-2022 走看看