-
Notifications
You must be signed in to change notification settings - Fork 27
/
220. Contains Duplicate III.c
65 lines (56 loc) · 1.75 KB
/
220. Contains Duplicate III.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
220. Contains Duplicate III
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
*/
typedef struct {
int val;
int idx;
} e_t;
int cmp(void const *a, void const *b) {
return ((const e_t *)a)->val < ((const e_t *)b)->val ? -1 :
((const e_t *)a)->val > ((const e_t *)b)->val ? 1 :
((const e_t *)a)->idx < ((const e_t *)b)->idx ? -1 : 1;
}
bool containsNearbyAlmostDuplicate(int* nums, int numsSize, int k, int t) {
e_t *p;
int i, j, d, f;
p = malloc(numsSize * sizeof(e_t));
//assert(p);
for (i = 0; i < numsSize; i ++) {
p[i].val = nums[i];
p[i].idx = i;
}
qsort(p, numsSize, sizeof(e_t), cmp);
f = 0;
for (i = 0; !f && i < numsSize - 1; i ++) {
//printf("\n%d: %d\n", p[i].idx, p[i].val);
for (j = i + 1;
!f &&
j < numsSize &&
((p[i].val > 0 && p[j].val - p[i].val <= t) ||
p[j].val <= t + p[i].val);
j ++) {
//printf("%d: %d\n", p[j].idx, p[j].val);
d = p[j].idx - p[i].idx;
if (d < 0) d = -d;
if (d <= k) f = 1;
}
}
free(p);
return f;
}
/*
Difficulty:Medium
Total Accepted:55.6K
Total Submissions:291K
Companies Palantir Airbnb
Related Topics Binary Search Tree
Similar Questions
Contains Duplicate
Contains Duplicate II
*/