Algorithm to determine if array contains n…n+m?

前端 未结 30 3122
清酒与你
清酒与你 2020-11-28 01:45

I saw this question on Reddit, and there were no positive solutions presented, and I thought it would be a perfect question to ask here. This was in a thread about interview

30条回答
  •  情歌与酒
    2020-11-28 02:14

    def test(a, n, m):
        seen = [False] * m
        for x in a:
            if x < n or x >= n+m:
                return False
            if seen[x-n]:
                return False
            seen[x-n] = True
        return False not in seen
    
    print test([2, 3, 1], 1, 3)
    print test([1, 3, 1], 1, 3)
    print test([1, 2, 4], 1, 3)
    

    Note that this only makes one pass through the first array, not considering the linear search involved in not in. :)

    I also could have used a python set, but I opted for the straightforward solution where the performance characteristics of set need not be considered.

    Update: Smashery pointed out that I had misparsed "constant amount of memory" and this solution doesn't actually solve the problem.

提交回复
热议问题