일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- Swift코딩테스트
- 프로그래머스
- algorithm
- IOS
- Safari Inspector
- SWIFT
- Di
- firestore
- five lines of cdde
- TDD
- alamofire
- 코딩테스트입문
- hackerrank
- css학습
- five lines of code
- 카카오맵클론
- 앱의생명주기
- RxSwift
- ARC
- unittest
- ios면접
- AutoLayout
- Swift디자인패턴
- mrc
- UIKit
- RC
- firebase
- 클린코드
- 리팩터링
- storekit2
- Today
- Total
샘성의 iOS 개발 일지
[Warm Up] Diagonal Difference 본문
문제 설명:
Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix is shown below:
1 2 3
4 5 6
9 8 9
The left-to-right diagonal = 1 + 5 + 9 = 15. The right to left diagonal = 9 + 5 + 3 = 17. Their absolute difference is |15 - 17|.
Complete the diagonalDifference function in the editor below.
diagonalDifference takes the following parameter:
* int arr[n][m]: an array of integers
Return
* int: the absolute diagonal difference
Input Format
The first line contains a single integer, n, the number of rows and columns in the square matrix arr.
Each of the next lines describes a row, arr[i], and consists of space-separated integers arr[i][j].
Output Format
Return the absolute difference between the sums of the matrix's two diagonals as a single integer.
내 풀이:
func diagonalDifference(arr: [[Int]]) -> Int {
var rightSideResult = 0
var leftSideResult = 0
guard let arrayCount = arr.last?.count else { return 0 }
for i in 0...arrayCount-1 {
// 0번째 배열의 0번째 index부터 arrayCount-1번째 배열의 arrayCount-1번째 index까지 더하기
rightSideResult += arr[i][i]
// 맨 밑의 배열의 0번째 index부터 거슬러 올라오면서 더해오기
leftSideResult += arr[arrayCount-1-i][i]
}
// 절대값 구하기
return abs(leftSideResult - rightSideResult)
}
회고:
처음에 abs()가 생각나지 않아 UInt()로 바꾼 후, 다시 Int()로 바꾸는 형식으로 풀었다. 역시나 50%의 정답률과 50%의 런타임 오류로 인해 탈락... 절대값 구하는 abs, 이번 기회에 잊지 말자
'Algorithm > HackerRank' 카테고리의 다른 글
[Implementation] Apple and Orange (0) | 2023.05.12 |
---|---|
[Implementation] Grading Students (0) | 2023.05.12 |
[Warm Up] Time Conversion (0) | 2023.05.11 |
[Warm Up] Birthday Cake Candles (0) | 2023.05.11 |
[Warm Up] Staircase (0) | 2023.05.11 |