-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubArrayWithEqualX&Y.java
92 lines (73 loc) · 2.12 KB
/
SubArrayWithEqualX&Y.java
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
80
81
82
83
84
85
86
87
88
89
90
91
/*
Problem Description
Given an integer array A and two integers B and C.
You need to find the number of subarrays in which the number of occurrences of B is equal to number of occurrences of C.
NOTE: Don't count empty subarrays.
Problem Constraints
1 <= |A| <= 104
1 <= A[i], B, C <= 108
B != C
Input Format
First argument is an integer array A.
Second argument is an integer B.
Third argument is an integer C.
Output Format
Return an integer denoting the number of subarrays in which the number of occurrences of B is equal to number of occurrences of C.
Example Input
Input 1:
A = [1, 2, 1]
B = 1
C = 2
Input 2:
A = {1, 2, 1}
B = 4
C = 6
Example Output
Output 1:
2
Output 2:
6
Example Explanation
Explanation 1:
The possible sub-arrays have same equal number of occurrences of B and C are:
1) {1, 2}, B and C have same occurrence(1).
2) {2, 1}, B and C have same occurrence(1).
Explanation 2:
The possible sub-arrays have same equal number of occurrences of B and C are:
1) {1}, B and C have same occurrence(0).
2) {2}, B and C have same occurrence(0).
3) {1}, B and C have same occurrence(0).
4) {1, 2}, B and C have same occurrence(0).
5) {2, 1}, B and C have same occurrence(0).
6) {1, 2, 1}, B and C have same occurrence(0).
*/
public class Solution {
public int solve(ArrayList<Integer> A, int B, int C) {
HashMap<Integer,Integer> map = new HashMap<>();
int ans = 0;
int countB = 0;
int countC = 0;
for(int i=0; i<A.size(); i++){
if(A.get(i) == B){
countB++;
}
if(A.get(i) == C){
countC++;
}
int x = countB - countC;
if(map.containsKey(x)){
ans = ans + map.get(x);
}
if(countB == countC){
ans = ans + 1;
}
if(map.containsKey(x)){
map.put(x,map.get(x)+1);
}
else{
map.put(x,1);
}
}
return ans;
}
}