不重复打印定值二元组_python3

不重复打印排序数组中相加和为给定值的所有二元组

http://www.nowcoder.com/questionTerminal/1ff1a607c81748baa1823ffa687d74c4

需要考虑重复数据的问题,开始没有想到用双指针,后来解决了,是in在list和dict查找的效率问题,严格一点空间复杂度过不了
1、超时

n, k = map(int, input().split())
l = list(map(int, input().split()))
for i in range(n-1):
    x = k - l[i]
    if x < l[i]:
        break
    if x in l:
        if i > 0 and l[i] == l[i-1] or l[i] == x and l.count(l[i]) == 1:
            continue
        print(l[i], x)

2、AC 136ms

n, k = map(int, input().split())
l = list(map(int, input().split()))
m = {}
for i in range(n):
    m[l[i]] = 1 if l[i] not in m.keys() else m[l[i]] + 1
for i in range(n-1):
    x = k - l[i]
    if x < l[i]:
        break
    if x in m.keys():
        if i > 0 and l[i] == l[i-1] or l[i] == x and m[l[i]] == 1:
            continue
        print(l[i], x)
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务