-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathArrayPairSumDivisibilityProblem.java
56 lines (51 loc) · 1.54 KB
/
ArrayPairSumDivisibilityProblem.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
/*https://practice.geeksforgeeks.org/problems/array-pair-sum-divisibility-problem3257/1/*/
class Solution {
public boolean canPair(int[] nums, int k) {
// Code here
int sum = 0, n = nums.length, i;
for (i = 0; i < n; ++i) sum += nums[i];
if (sum%k != 0) return false;
boolean turn = true;
for (i = 0; i < n; ++i)
{
nums[i] = nums[i]%k;
if (nums[i] == 0)
{
if (turn) nums[i] = k;
turn = !turn;
}
}
int pairs = 0;
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for (i = 0; i < n; ++i)
{
if (map.containsKey(k-nums[i]) && (Integer)map.get(k-nums[i]) > 1)
{
map.put(k-nums[i],(Integer)map.get(k-nums[i])-1);
++pairs;
}
else if (map.containsKey(k-nums[i]))
{
map.remove(k-nums[i]);
++pairs;
}
else map.put(nums[i],(map.containsKey(nums[i]) ? (Integer)map.get(nums[i])+1 : 1));
}
if (map.size() == 0) return true;
return false;
}
}
class Solution {
public boolean canPair(int[] nums, int k) {
// Code here
int[] rem = new int[k];
for (int x : nums)
++rem[x % k];
if (rem[0] % 2 != 0)
return false;
for (int i = 1; i < k; ++i)
if (rem[i] != rem[k - i])
return false;
return true;
}
}