Leetcode 1313. 解压缩编码列表

74 阅读1分钟

Table of Contents

中文版:

英文版:

My answer:

学习:


中文版:

给你一个以行程长度编码压缩的整数列表 nums 。

考虑每相邻两个元素 [a, b] = [nums[2*i], nums[2*i+1]] (其中 i >= 0 ),每一对都表示解压后有 a 个值为 b 的元素。

请你返回解压后的列表。

示例:

输入:nums = [1,2,3,4]
输出:[2,4,4,4]

提示:

  • 2 <= nums.length <= 100
  • nums.length % 2 == 0
  • 1 <= nums[i] <= 100

英文版:

5143. Decompress Run-Length Encoded List

We are given a list nums of integers representing a list compressed with run-length encoding.

Consider each adjacent pair of elements [a, b] = [nums[2*i], nums[2*i+1]] (with i >= 0).  For each such pair, there are a elements with value b in the decompressed list.

Return the decompressed list.

Example 1:

Input: nums = [1,2,3,4] Output: [2,4,4,4]

Constraints:

  • 2 <= nums.length <= 100
  • nums.length % 2 == 0
  • 1 <= nums[i] <= 100

 

My answer:

class Solution:
    def decompressRLElist(self, nums: List[int]) -> List[int]:
        result = []
        for i in range(len(nums)):
            if i % 2 == 0:
                a = nums[i]
            else:
                b = nums[i]
                result += a * [b]
            
        return result
        

学习:

1、a * [b] 表示生成列表,列表中有 a 个 b。

2、result += a * [b],可理解为列表的拼接,注意与 append() 函数的区别。