Remove all occurrences of a value from a list?

后端 未结 23 2548
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 23:45

In Python remove() will remove the first occurrence of value in a list.

How to remove all occurrences of a value from a list?

This is w

23条回答
  •  佛祖请我去吃肉
    2020-11-22 00:18

    No one has posted an optimal answer for time and space complexity, so I thought I would give it a shot. Here is a solution that removes all occurrences of a specific value without creating a new array and at an efficient time complexity. The drawback is that the elements do not maintain order.

    Time complexity: O(n)
    Additional space complexity: O(1)

    def main():
        test_case([1, 2, 3, 4, 2, 2, 3], 2)     # [1, 3, 3, 4]
        test_case([3, 3, 3], 3)                 # []
        test_case([1, 1, 1], 3)                 # [1, 1, 1]
    
    
    def test_case(test_val, remove_val):
        remove_element_in_place(test_val, remove_val)
        print(test_val)
    
    
    def remove_element_in_place(my_list, remove_value):
        length_my_list = len(my_list)
        swap_idx = length_my_list - 1
    
        for idx in range(length_my_list - 1, -1, -1):
            if my_list[idx] == remove_value:
                my_list[idx], my_list[swap_idx] = my_list[swap_idx], my_list[idx]
                swap_idx -= 1
    
        for pop_idx in range(length_my_list - swap_idx - 1):
            my_list.pop() # O(1) operation
    
    
    if __name__ == '__main__':
        main()
    

提交回复
热议问题