我可以在不创建新列表/数组的情况下展平数组吗?

问题描述

假设我有arr = [[1],[0,0],[2],[3],[4]]

是否可以不必使用itertools,map / reduce或list comp将其展平为[1,2,3,4]?我正在努力想办法做到这一点。谢谢。

这是我到目前为止尝试过的,这是一个leetcode问题:https://leetcode.com/problems/duplicate-zeros/

class Solution:
    def duplicateZeros(self,arr: List[int]) -> None:
        """
        Do not return anything,modify arr in-place instead.
        
        """
        for ix in range(len(arr) - 2):
            if arr[ix] == 0:
                arr[ix] = [0,0]
                del arr[-1]
            else:
                l = []
                l.append(arr[ix])
                arr[ix] = l

# Output when you return arr is [[1],[4]]

解决方法

尝试一些递归:

def flatten(lst):
    ans = []
    for el in lst:
        if type(el) == list:
             for e in flatten(el):
                 ans.append(e)
        else:
            ans.append(el)
    return ans

它将拼合任意维度的列表。

,

您可以轻松地做到:

arr = sum(arr,[])

您在这里要做的是添加arr的可迭代元素,并将空数组[]作为初始值。

,
  • 我们也可以在此处使用list copy[:])来解决问题:
class Solution:
    def duplicateZeros(self,A):
        """
        Do not return anything,modify arr in-place instead.
        """
        A[:] = [x for num in A for x in ([num] if num else [0,0])][:len(A)]
  • 此外,最佳解决方案是具有恒定内存的N个运行时的顺序。 LeetCode here已经解决了这个问题:
class Solution:
    def duplicateZeros(self,arr: List[int]) -> None:
        """
        Do not return anything,modify arr in-place instead.
        """

        possible_dups = 0
        length_ = len(arr) - 1

        # Find the number of zeros to be duplicated
        for left in range(length_ + 1):

            # Stop when left points beyond the last element in the original list
            # which would be part of the modified list
            if left > length_ - possible_dups:
                break

            # Count the zeros
            if arr[left] == 0:
                # Edge case: This zero can't be duplicated. We have no more space,# as left is pointing to the last element which could be included  
                if left == length_ - possible_dups:
                    arr[length_] = 0 # For this zero we just copy it without duplication.
                    length_ -= 1
                    break
                possible_dups += 1

        # Start backwards from the last element which would be part of new list.
        last = length_ - possible_dups

        # Copy zero twice,and non zero once.
        for i in range(last,-1,-1):
            if arr[i] == 0:
                arr[i + possible_dups] = 0
                possible_dups -= 1
                arr[i + possible_dups] = 0
            else:
                arr[i + possible_dups] = arr[i]