-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestsubseq.cpp
More file actions
79 lines (65 loc) · 1.67 KB
/
longestsubseq.cpp
File metadata and controls
79 lines (65 loc) · 1.67 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
using namespace std;
const int HASH_SIZE = 200003; // A large prime number
const int EMPTY = 2000000001; // Sentinel value for empty slot
class HashSet {
int* table;
public:
HashSet() {
table = new int[HASH_SIZE];
for (int i = 0; i < HASH_SIZE; i++) {
table[i] = EMPTY;
}
}
int hash(int key) {
long long h = (1LL * key % HASH_SIZE + HASH_SIZE) % HASH_SIZE;
return (int)h;
}
void insert(int key) {
int h = hash(key);
while (table[h] != EMPTY && table[h] != key) {
h = (h + 1) % HASH_SIZE;
}
table[h] = key;
}
bool contains(int key) {
int h = hash(key);
int start = h;
while (table[h] != EMPTY) {
if (table[h] == key) return true;
h = (h + 1) % HASH_SIZE;
if (h == start) break;
}
return false;
}
~HashSet() {
delete[] table;
}
};
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
int n = nums.size();
if (n == 0) return 0;
HashSet set;
for (int i = 0; i < n; i++) {
set.insert(nums[i]);
}
int maxLen = 0;
for (int i = 0; i < n; i++) {
int num = nums[i];
if (!set.contains(num - 1)) {
int currentNum = num;
int streak = 1;
while (set.contains(currentNum + 1)) {
currentNum++;
streak++;
}
if (streak > maxLen) {
maxLen = streak;
}
}
}
return maxLen;
}
};