In less-than-linear time, find the duplicate in a sorted array

前端 未结 7 1466
名媛妹妹
名媛妹妹 2020-12-31 11:00

Today, an interviewer asked me this question. My immediate response was that we could simply do a linear search, comparing the current element with the previous element in t

7条回答
  •  礼貌的吻别
    2020-12-31 11:09

    Difference between sum of given array elements and sum of 0 to n-1 natural numbers gives you the duplicated element. Sum of 0 to n-1 elements is (N * N-1)/2 example array is [0,1,2,3,4,5,6,7,8,8,9] sum of 0 to 9 natural numbers is : 45 sum of given array elements : 53 53-45 = 8 Which is the duplicated element

提交回复
热议问题