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

前端 未结 7 1465
名媛妹妹
名媛妹妹 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:15

    #include 
    using namespace std;
    
    int find_only_repeating_element(int arr[] , int n){
    int low = 0;
    int high = n-1;
    while(low <= high){
        int mid = low + (high - low)/2;
        if(arr[mid] == arr[mid + 1] || arr[mid] == arr[mid - 1]){
            return arr[mid];
        }
        if(arr[mid] < mid + 1){
            high = mid - 2;
        }else{
            low = mid + 1;
        }
       }
       return -1;
    }
    
    int main(int argc, char const *argv[])
    {
    int n , *arr;
    cin >> n;
    arr = new int[n];
    for(int i = 0 ; i < n ; i++){
        cin >> arr[i];
    }
        cout << find_only_repeating_element(arr , n) << endl;
        return 0;
    }
    

提交回复
热议问题