Find the unduplicated element in a sorted array

后端 未结 3 438
情书的邮戳
情书的邮戳 2021-01-18 05:54

Source : Microsoft Interview Question

Given a sorted array, in which every element is present twice except one which is present single time

3条回答
  •  时光说笑
    2021-01-18 06:51

    Yes, you can use the sortedness to reduce the complexity to O(log n) by doing a binary search.

    Since the array is sorted, before the missing element, each value occupies the spots 2*k and 2*k+1 in the array (assuming 0-based indexing).

    So you go to the middle of the array, say index h, and check either index h+1 if h is even, or h-1 if h is odd. If the missing element comes later, the values at these positions are equal, if it comes before, the values are different. Repeat until the missing element is located.

提交回复
热议问题