微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如果数组中的两个连续数字相等,如何缩小数组,然后删除一个并递增其他

如何解决如果数组中的两个连续数字相等,如何缩小数组,然后删除一个并递增其他

如果数组中的两个连续数字相等,如何缩小数组,然后删除一个并递增另一个

Ex:int a [6] = {2,2,3,4,4}; 输出:6

Ex:int b [7] = {1,4}; 输出:{1,4}

解决方法

这可以在接近线性的时间内完成,例如:

a = [2,2,3,4,4]
b = [1,4]
c = [5,5,1]

def shrink_array(a):
    res = []
    
    for i in range(1,len(a)+1):
        if i < len(a) and a[i] == a[i-1]: # if equal to previous
            a[i] += 1 # increment and move on
        else:
            if len(res) > 0 and res[-1] == a[i-1]: # if equal to last in res
                res[-1] += 1 # increment last in res
            else:
                res.append(a[i-1]) # add to res

        while len(res) > 1 and res[-1] == res[-2]: # shrink possible duplicates
            res[-2] += 1
            del res[-1]
        
    return(res)

for arr in [a,b,c]:
    print(shrink_array(arr))

输出:

[6]
[1,4]
[6,1]
,
lst = [2,4]
    
def shrink(lst):
    idx = 0
    while len(lst) > idx+1:
        a,b = lst.pop(idx),lst.pop(idx)

        if a == b:
            lst.insert(idx,a+1)
            idx = 0
        else:
            lst.insert(idx,b)
            lst.insert(idx,a)
            idx += 1

shrink(lst)
print(lst)

打印:

[6]

对于[5,1]打印[6,1]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。