Problem
You are given an array of integers, , and a positive integer, . Find and print the number of pairs where and + is divisible by .
For example, and . Our three pairs meeting the criteria are and .
Function Description
Complete the divisibleSumPairs function in the editor below. It should return the integer count of pairs meeting the criteria.
divisibleSumPairs has the following parameter(s):
- n: the integer length of array
- ar: an array of integers
- k: the integer to divide the pair sum by
Input Format
The first line contains space-separated integers, and .
The second line contains space-separated integers describing the values of .
Constraints
Output Format
Print the number of pairs where and + is evenly divisible by .
Sample Input
6 3
1 3 2 6 1 2
Sample Output
5
Explanation
Here are the 5 valid pairs when k = 3:
* (0, 2) → ar[0] + ar[2] = 1 + 2 = 3
* (0, 5) → ar[0] + ar[5] = 1 + 2 = 3
* (1, 3) → ar[1] + ar[3] = 3 + 6 = 9
* (2, 4) → ar[2] + ar[4] = 2 + 1 = 3
* (4, 5) → ar[4] + ar[5] = 1 + 2 = 3
How I solved the problem
# 배열이 연속하는 수가 아니기 때문에 이중 반복문이 돌아야함!
# 같은 배열이 겹치지 않도록 반복문을 짜는게 중요함.
# i가 0이라면 j는 1부터 시작하도록 해서 j가 1보다 항상 크게 시작하도록 짜는 것이 중요
# 나누어질 수 있는 배열의 합의 개수를 리턴해야하기 때문에 나머지 함수 %가 0이 되는 것을 찾기
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 | import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class Solution { // Complete the divisibleSumPairs function below. static int divisibleSumPairs(int n, int k, int[] ar) { int result = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) {//at least, j is bigger than i int sum = ar[i] + ar[j]; //sum a pair of ar if (sum % k == 0) { //test if the sum is divisible result++; } } } return result; } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); String[] nk = scanner.nextLine().split(" "); int n = Integer.parseInt(nk[0]); int k = Integer.parseInt(nk[1]); int[] ar = new int[n]; String[] arItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < n; i++) { int arItem = Integer.parseInt(arItems[i]); ar[i] = arItem; } int result = divisibleSumPairs(n, k, ar); bufferedWriter.write(String.valueOf(result)); bufferedWriter.newLine(); bufferedWriter.close(); scanner.close(); } } | cs |
[출처 : https://www.hackerrank.com ]
'1 Day 1 Algorithms' 카테고리의 다른 글
[2019.02.13] Day of the Programmer (0) | 2019.02.13 |
---|---|
[2019.02.12] Migratory Birds (0) | 2019.02.12 |
[2019.02.08] Birthday Chocolate (0) | 2019.02.08 |
[2019.02.01] Breaking the Records (0) | 2019.02.01 |
[2019.01.31] Between Two Sets (0) | 2019.01.31 |
댓글