LeetCode Contains Duplicate III

Source: Internet
Author: User

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 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.