넘치게 채우기

[LeetCode] 1572. Matrix Diagonal Sum 본문

PS/LeetCode

[LeetCode] 1572. Matrix Diagonal Sum

riveroverflow 2023. 5. 8. 11:31
728x90
반응형

https://leetcode.com/problems/matrix-diagonal-sum/description/

 

Matrix Diagonal Sum - LeetCode

Can you solve this real interview question? Matrix Diagonal Sum - Given a square matrix mat, return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are

leetcode.com

문제 유형 : 투 포인터

문제 난이도 : Easy

 

문제

Given a square matrix mat, return the sum of the matrix diagonals.

Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.

정사각형 2차원 배열 mat의 대각선 수들의 합을 구해라. 단, 겹치는 부분은 한 번만 더한다.

 

풀이

투 포인터로 쉽게 풀 수 있다.

값이 중복되는 경우는 정사각형의 길이가 홀수인 경우인데, 그 때 정 중앙에 있는값만 한번 빼주면 중복처리를 할 수 있다.

 

코드(C++)

class Solution {
public:
    int diagonalSum(vector<vector<int>>& mat) {
        int n = mat.size();
        int sum = 0;
        int mid = n/2;
        if(n == 1){
            return mat.at(0).at(0);
        }
    
        for(int i = 0; i < n; i++){
            sum += mat.at(i).at(i);
            sum += mat.at(i).at(n-i-1);
        }
        if(n % 2 == 1){
            int mid = n/2;
            sum -= mat.at(mid).at(mid);
        }
    
        return sum;
    }

};
728x90
반응형