整型数组(一)

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.ExampleGiven an array [0,4,4,0,0,2,4,4], value=4return 4 and front four elements of the array is [0,0,0,2]

def remove(s,value,length):
    if s is None: return False
    a=[]
    for i in range(len(s)):
        if s[i]!=value and len(a)<length: a.append(s[i])
    return a

s=[0,4,4,0,0,2,4,4]
value=4
length=4
remove(s,value,length)



Zero Sum Subarray

Given an integer array, find a subarray where the sum of numbers is zero.
Your code should return the index of the first number and the index of the last number.

Example
Given [-3, 1, 2, -3, 4], return [0, 2] or [1, 3].

Note
There is at least one subarray that it's sum equals to zero.
def zero_sum(s):
    c=[]
    for i in range(int(len(s)/2)+1):
        a=[]
        b=[]
        for j in range(len(s)-1-i):
            a=s[i:j+i+1]
            if np.sum(a)==0: b.append([i,j+i])
        if b!=[]:c.append(b)
    return c

s=[-3, 1, 2, -3, 4]
zero_sum(s)

Note:

1. At first I try to add i+1 to range(len(s)-1+i), but this operation will connect two lists together. Finally I find change to [i:i+j] is useful.

2.About loop: tab means executing the correlated operations.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值