-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathCheckIfAll1sAreAtLeastLengthKAway.cpp
More file actions
58 lines (55 loc) · 1.19 KB
/
Copy pathCheckIfAll1sAreAtLeastLengthKAway.cpp
File metadata and controls
58 lines (55 loc) · 1.19 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
// Method - 1
class Solution
{
public:
bool kLengthApart(vector<int> &nums, int k)
{
int start = -1;
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] == 1)
{
if (start != -1 && i - start - 1 < k)
return false;
start = i;
}
}
return true;
}
};
// Time Complexity - O(N)
// Space Complexity - O(1)
// Method - 2
class Solution
{
public:
bool kLengthApart(vector<int> &nums, int k)
{
int start = -1;
int end = -1;
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] == 1 && start == -1)
{
start = i;
}
else if (nums[i] == 1 && end == -1)
{
end = i;
}
if (start != -1 && end != -1 && (end - start - 1) < k)
{
return false;
}
if (start != -1 && end != -1)
{
int temp = start;
start = end;
end = -1;
}
}
return true;
}
};
// Time Complexity - O(N)
// Space Complexity - O(1)