the second one in Weekly Contest 195.
Given an array of integers
arr
of even lengthn
and an integerk
.We want to divide the array into exactly
n / 2
pairs such that the sum of each pair is divisible byk
.Return True If you can find a way to do that or False otherwise.
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5 Output: true Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
Input: arr = [1,2,3,4,5,6], k = 7 Output: true Explanation: Pairs are (1,6),(2,5) and(3,4).
Input: arr = [1,2,3,4,5,6], k = 10 Output: false Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Input: arr = [-10,10], k = 2 Output: true
Input: arr = [-1,1,-2,2,-3,3,-4,4], k = 3 Output: true
arr.length == n
1 <= n <= 10^5
n
is even.-10^9 <= arr[i] <= 10^9
1 <= k <= 10^5
- mine
- Java
-
Time Limit Exceeded
// O(N^2)time O(N)space public boolean canArrange(int[] arr, int k) { int len = arr.length; boolean[] t = new boolean[len]; for(int i = 0; i < len; i++){ if(t[i]){ continue; } for(int j = i + 1; j < len; j++){ if(t[j]){ continue; } if((arr[i] + arr[j]) % k == 0){ t[i] = true; t[j] = true; break; } } } boolean res = true; for(boolean b : t){ res &= b; } return res; }
-
Runtime: 10 ms, faster than 64.41%, Memory Usage: 79.5 MB, less than 100.00% of Java online submissions
// O(M)time O(K)space // M = max(arr.length, k/2) public boolean canArrange(int[] arr, int k) { int len = arr.length; int[] record = new int[k]; for(int i = 0; i < len; i++){ int mod = (arr[i] % k + k) % k; record[mod]++; } if(record[0] % 2 != 0){ return false; } for(int i = 1; i <= k / 2; i++){ if(record[i] != record[k - i]){ return false; } } return true; }
-
- Java