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

前端 未结 30 3176
清酒与你
清酒与你 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 01:55

    By working with a[i] % a.length instead of a[i] you reduce the problem to needing to determine that you've got the numbers 0 to a.length - 1.

    We take this observation for granted and try to check if the array contains [0,m).

    Find the first node that's not in its correct position, e.g.

    0 1 2 3 7 5 6 8 4 ;     the original dataset (after the renaming we discussed)
            ^
            `---this is position 4 and the 7 shouldn't be here
    

    Swap that number into where it should be. i.e. swap the 7 with the 8:

    0 1 2 3 8 5 6 7 4 ; 
            |     `--------- 7 is in the right place.
            `--------------- this is now the 'current' position
    

    Now we repeat this. Looking again at our current position we ask:

    "is this the correct number for here?"

    • If not, we swap it into its correct place.
    • If it is in the right place, we move right and do this again.

    Following this rule again, we get:

    0 1 2 3 4 5 6 7 8 ;     4 and 8 were just swapped
    

    This will gradually build up the list correctly from left to right, and each number will be moved at most once, and hence this is O(n).

    If there are dupes, we'll notice it as soon is there is an attempt to swap a number backwards in the list.

提交回复
热议问题