Skip to content

Commit d4ae0fc

Browse files
committed
Add C++ solution of problem #3152
1 parent 3c0f8f7 commit d4ae0fc

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Diff for: 3152/solution.cpp

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// use binary search to the start in interval then check whether end is in the same interval of start or not
2+
3+
class Solution {
4+
public:
5+
vector<bool> isArraySpecial(vector<int>& A, vector<vector<int>>& queries) {
6+
int n = A.size();
7+
8+
vector<bool> ans(queries.size(), false);
9+
int idx = 0; // start index of special
10+
int cur = A[0];
11+
vector<int> start, end; // start and end of specials
12+
int i;
13+
for(i = 1; i < n; i++) {
14+
if(
15+
(cur % 2 == 0 && A[i] % 2 == 1) ||
16+
(cur % 2 == 1 && A[i] % 2 == 0)
17+
) {
18+
// switch
19+
cur = A[i];
20+
continue;
21+
}
22+
23+
start.push_back(idx);
24+
end.push_back(i - 1);
25+
idx = i;
26+
cur = A[i];
27+
}
28+
// deal with leftover
29+
if(i - idx > 1) {
30+
start.push_back(idx);
31+
end.push_back(i - 1);
32+
}
33+
34+
for(i = 0; i < queries.size(); i++) {
35+
int s = queries[i][0];
36+
int e = queries[i][1];
37+
int ii = b_search(start, s);
38+
39+
if(
40+
(s == e) ||
41+
(ii < start.size() && e <= end[ii])
42+
)
43+
ans[i] = true;
44+
}
45+
46+
return ans;
47+
}
48+
49+
private:
50+
// Return the index of less than or equal to target.
51+
int b_search(vector<int> &A, int target) {
52+
int l = 0;
53+
int r = A.size();
54+
while(l < r) {
55+
int m = l + (r - l) / 2;
56+
if(A[m] <= target)
57+
l = m + 1;
58+
else
59+
r = m;
60+
}
61+
return l - 1;
62+
}
63+
};

0 commit comments

Comments
 (0)