LeetCode Contains Duplicate III
LeetCode Contains Duplicate III
Ideas
My method is to first use a struct to store the values of each number and their original coordinates;
Then sort by value size;
Then traverse each number num [I]. val;
Use binary search to find the coordinates of a number that is just greater than num [I]. val-t-1;
Then, you can determine whether a value exists based on the coordinates;
Binary Search: Binary Search
Code
Struct num {int pos, val;}; int AD (struct num * nums, int l, int r) {int K = nums [l]. val; int Kp = nums [l]. pos; while (l <r) {while (l <r & nums [r]. val> K) r --; if (l <r) nums [l ++] = nums [r]; while (l <r & nums [l]. val <K) l ++; if (l <r) nums [r --] = nums [l];} nums [l]. val = K; nums [l]. pos = Kp; return l;} void QS (struct num * nums, int l, int r) {if (l <r) {int mid = AD (nums, l, r); QS (nums, l, mid-1); QS (nums, mid + 1, r );}} // In the sequence that does not drop, find the position where the number appears exactly greater than the target, that is, the first position where the number appears greater than the target int binarySearchIncreaseFirstBigger (struct num * nums, int l, int r, int target) {if (r-l + 1 = 0) return-1; while (l <r) {int m = l + (r-l)> 1); if (nums [m]. val <= target) l = m + 1; else r = m;} if (nums [r]. val> target) return r; else return-1;} bool containsNearbyAlmostDuplicate (int * nums, int numsSize, int k, int t) {struct num * N = (struct num *) malloc (sizeof (struct num) * numsSize); for (int I = 0; I <numsSize; I ++) N [I]. pos = I, N [I]. val = nums [I]; QS (N, 0, numsSize-1); for (int I = 1; I <numsSize; I ++) {int minPos = binarySearchIncreaseFirstBigger (N, 0, I-1, N [I]. val-t-1); if (minPos =-1) {} else {for (int j = minPos; j <I; j ++) {if (abs (N [I]. pos-N [j]. pos) <= k) {free (N); return true ;}}} free (N); return false ;}