Given a string of a million numbers, return all repeating 3 digit numbers

前端 未结 13 1509
误落风尘
误落风尘 2020-12-22 15:41

I had an interview with a hedge fund company in New York a few months ago and unfortunately, I did not get the internship offer as a data/software engineer. (They also asked

13条回答
  •  Happy的楠姐
    2020-12-22 16:12

    The simple O(n) solution would be to count each 3-digit number:

    for nr in range(1000):
        cnt = text.count('%03d' % nr)
        if cnt > 1:
            print '%03d is found %d times' % (nr, cnt)
    

    This would search through all 1 million digits 1000 times.

    Traversing the digits only once:

    counts = [0] * 1000
    for idx in range(len(text)-2):
        counts[int(text[idx:idx+3])] += 1
    
    for nr, cnt in enumerate(counts):
        if cnt > 1:
            print '%03d is found %d times' % (nr, cnt)
    

    Timing shows that iterating only once over the index is twice as fast as using count.

提交回复
热议问题