Leetcode 89. Gray Code

Problem

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has a size equal to m + n such that it has enough space to hold additional elements from nums2.

Algorithm

The i-th gray code number is G i = B i x o r B i − 1 G_i = B_i \mathbf{xor} B_{i-1} Gi=BixorBi1, where B i B_i Bi is the i-th binary code number.

Code

class Solution:
    def grayCode(self, n: int) -> List[int]:
        gray = []
        for i in range(1<<n):
            gray.append(i^(i>>1))
        
        return gray

你可能感兴趣的:(解题报告)