샘성의 iOS 개발 일지

[Implementation] Divisible Sum Pairs 본문

Algorithm/HackerRank

[Implementation] Divisible Sum Pairs

SamusesApple 2023. 5. 17. 13:07
728x90

문제 설명:

  Given an array of integers and a positive integer k, determine the number of [i, j] pairs where i < j and ar[i] + ar[j] is divisible by k.

 

Example

ar = [1, 2, 3, 4, 5, 6]
k = 5

Three pairs meet the criteria: [1, 4], [2, 3] and [4, 6].

 

Function Description

Complete the divisibleSumPairs function in the editor below.

divisibleSumPairs has the following parameter(s):

  • int n: the length of array ar
  • int ar[n]: an array of integers
  • int k: the integer divisor

Returns
- int: the number of pairs

 

 

 

내 풀이:

func divisibleSumPairs(n: Int, k: Int, ar: [Int]) -> Int {
    var resultArrays = [[Int]]()
    
    // value1와 value2의 합이 k로 나누어떨어지는 모든 순열 구하기
    for (index1, value1) in ar.enumerated() {
        for (index2, value2) in ar.enumerated() {
            if index1 != index2 {
                let newArray = [value1, value2]
                if (newArray[0] + newArray[1]) % k == 0 {
                    resultArrays.append(newArray)
                }
            }
        }
    }
 	// 대신, 순열이기에 [1, 3], [3, 1]과 같은 경우, 겹치게 되므로 2로 나누기
    return resultArrays.count / 2
}

 

 

 

회고:

  for loop문을 중첩하지 않고 풀 수 있는 방식에 대해 찾아보아야겠다....

728x90

'Algorithm > HackerRank' 카테고리의 다른 글

[Implementation] Sales by Match  (0) 2023.07.12
[Implementation] Migratory Birds  (0) 2023.05.17
[Implementation] Breaking the Records  (0) 2023.05.14
[Implementation] Between Two Sets  (0) 2023.05.14
[Implementation] Number Line Jumps  (0) 2023.05.12