Skip to content

Commit f39725f

Browse files
committed
Add 0496-next-greater-element-1.c
1 parent 73882c7 commit f39725f

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

c/0496-next-greater-element-i.c

+92
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
#define INIT_HASH_SIZE 1024
2+
3+
// Represent an element in a hash table.
4+
typedef struct Hash {
5+
int key;
6+
int value;
7+
struct Hash *next;
8+
} Hash;
9+
10+
// Use -1 as non-existed key,
11+
// as 0 <= nums1[i], nums2[i] <= 104
12+
Hash *InitHash() {
13+
Hash *h = (Hash*)calloc(INIT_HASH_SIZE, sizeof(Hash));
14+
assert(h);
15+
for (int i = 0; i < INIT_HASH_SIZE; i++) {
16+
h[i].key = -1;
17+
}
18+
return h;
19+
}
20+
21+
Hash *NewHash(int key, int value) {
22+
Hash *h = (Hash*)malloc(sizeof(Hash));
23+
assert(h);
24+
h->key = key;
25+
h->value = value;
26+
h->next = NULL;
27+
return h;
28+
}
29+
30+
int HashKey(int key) {
31+
while(key < 0) key += INIT_HASH_SIZE;
32+
return (key % INIT_HASH_SIZE);
33+
}
34+
35+
void SetHash(Hash *root, int key, int value) {
36+
assert(root);
37+
Hash *h = &root[HashKey(key)];
38+
if (h->key == -1) {
39+
h->key = key;
40+
h->value = value;
41+
} else if (h->key == key) {
42+
h->value = value;
43+
} else {
44+
while (h) {
45+
if (h->key == key) {
46+
h->value = value;
47+
return;
48+
} else if (!h->next) {
49+
h->next = NewHash(key, value);
50+
return;
51+
}
52+
h = h->next;
53+
}
54+
}
55+
}
56+
57+
// If hash not round return -1 on purpose.
58+
int GetHash(Hash *root, int key) {
59+
Hash *h = &root[HashKey(key)];
60+
while(h) {
61+
if (h->key == key) {
62+
return h->value;
63+
}
64+
h = h->next;
65+
}
66+
return -1;
67+
}
68+
69+
/**
70+
* Note: The returned array must be malloced, assume caller calls free().
71+
*/
72+
int* nextGreaterElement(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
73+
Hash *hash = InitHash();
74+
int *res = (int*)malloc(nums1Size*sizeof(int));
75+
int i, j;
76+
77+
for (i = 0; i < nums2Size; i++) {
78+
for (j = i + 1; j < nums2Size; j++) {
79+
if (nums2[j] > nums2[i]) {
80+
SetHash(hash, nums2[i], nums2[j]);
81+
break;
82+
}
83+
}
84+
}
85+
86+
for (i = 0; i < nums1Size; i++) {
87+
res[i] = GetHash(hash, nums1[i]);
88+
}
89+
90+
*returnSize = nums1Size;
91+
return res;
92+
}

0 commit comments

Comments
 (0)