-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprefix_common_array.cpp
More file actions
58 lines (53 loc) · 1.59 KB
/
prefix_common_array.cpp
File metadata and controls
58 lines (53 loc) · 1.59 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
/*
* =====================================================================================
*
* Filename: prefix_common_array.cpp
*
* Description: 2657. Find the Prefix Common Array of Two Arrays
* https://leetcode.com/problems/find-the-prefix-common-array-of-two-arrays/
*
* Version: 1.0
* Created: 01/15/2025 22:35:21
* Revision: none
* Compiler: gcc
*
* Author: xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <tuple>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using std::vector;
class Solution {
public:
vector<int> findThePrefixCommonArray(vector<int>& A, vector<int>& B) {
const int n = A.size();
vector<int> frequency(n, 0);
vector<int> prefix(n, 0);
for (int i = 0; i < n; i++) {
if (i > 0) {
prefix[i] += prefix[i - 1];
}
if (++frequency[A[i] - 1] > 1) {
prefix[i]++;
}
if (++frequency[B[i] - 1] > 1) {
prefix[i]++;
}
}
return prefix;
}
};
TEST(Solution, findThePrefixCommonArray) {
vector<std::tuple<vector<int>, vector<int>, vector<int>>> cases = {
std::make_tuple(vector<int>{1, 3, 2, 4}, vector<int>{3, 1, 2, 4}, vector<int>{0, 2, 3, 4}),
std::make_tuple(vector<int>{2, 3, 1}, vector<int>{3, 1, 2}, vector<int>{0, 1, 3}),
};
for (auto& c : cases) {
EXPECT_THAT(Solution().findThePrefixCommonArray(std::get<0>(c), std::get<1>(c)),
testing::ElementsAreArray(std::get<2>(c)));
}
}