数组-(Remove Element)移除指定数字返回新的数组

'''
Given an array and a value, remove all occurrences of that value in place and return the new length.

The order of elements can be changed, and the elements after the new length don't matter.

Example
Given an array [0,4,4,0,0,2,4,4], value=4

return 4 and front four elements of the array is [0,0,0,2]
'''

'''
一句话总结:拿两个指示变量i,j从0开始,i只负责遍历所有的值,j负责保存不包含elem的索引,i循环完了j的长度就是新的数组长度,新的数组内容就是0:j
'''


class Solution:
    def call(self, arr, elem):
        i = 0
        j = 0
        while i < len(arr):
            # 如果相当则忽略,进入下一个位置
            if arr[i] == elem:
                pass
            else:  # 如果不等,则加入新的以left为长度计算的arr
                arr[j] = arr[i]
                j += 1  # left长度加以
            i += 1  # 进入下一轮判断
        return (j, arr[0:j])


s = Solution()
print(s.call([0, 4, 4, 0, 0, 2, 4, 4, 1, 2, 3, 4, 8], 4))
#(8, [0, 0, 0, 2, 1, 2, 3, 8])

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值