You are viewing a single comment's thread. Return to all comments →
Sort the array then use binary search
bool binary_search(int* arr, int target, int l, int r){ while(l <= r){ int mid = l + (r-l)/2; if (arr[mid] == target){ return true; } else if (arr[mid] > target){ r = mid-1; } else{ l = mid+1; } } return false; } void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp; } int partition(int* arr, int l, int r){ int pivot = arr[r]; int start_idx = l; int bigger_idx = l; for (int i = start_idx; i<r; i++){ if (arr[i] < pivot){ swap(&arr[i], &arr[bigger_idx]); bigger_idx ++; } } swap(&arr[r], &arr[bigger_idx]); return bigger_idx; } int* my_q_sort(int* arr, int l, int r){ if (l < r){ int idx = partition(arr, l, r); my_q_sort(arr, l, idx-1); my_q_sort(arr, idx+1, r); } return arr; } int pairs(int k, int arr_count, int* arr) { int res_count = 0; arr = my_q_sort(arr, 0, arr_count-1); for (int i = 0; i<arr_count-1; i++){ bool find_pair = binary_search(arr, arr[i]+k, 0, arr_count-1); if (find_pair == true){ res_count ++; } } return res_count; }
Seems like cookies are disabled on this browser, please enable them to open this website
Pairs
You are viewing a single comment's thread. Return to all comments →
Sort the array then use binary search