본문 바로가기

코딩테스트/프로그래머스

[프로그래머스] 테이블 해시 함수

728x90
반응형


🔗 문제

https://school.programmers.co.kr/learn/courses/30/lessons/147354

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


반응형
728x90

👩‍💻 코드

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

int solution(vector<vector<int>> data, int col, int row_begin, int row_end) {
    int answer = 0;
    col--;
    row_begin--;
    row_end--;
    
    sort(data.begin(), data.end(), [col](const vector<int>& a, const vector<int>& b) {
        if(a[col] == b[col]){
            return a[0] > b[0];
        }else{
            return a[col] < b[col];
        }
    });
    
    for(int i=row_begin; i<=row_end; i++){
        int sum = 0;
        for(int j=0; j<data[i].size(); j++){
            sum += data[i][j] % (i+1);
        }
        answer ^= sum;
    }
    
    return answer;
}

📝 풀이

col, row_begin, row_end를 index와 맞추기 위해 1를 빼줍니다.

테이블의 튜플을 col번째 컬럼 기준으로 오름차순 정렬을 하고, 만약 값이 동일하다면 첫 번째 컬럼을 기준으로 내림차순 정렬을 합니다.

정렬된 데이터에서 S_i 값을 row_begin부터 row_end까지 구합니다.

모든 S_i값을 XOR 연산하여 answer에 저장합니다.

반복문이 종료되면 answer을 return 합니다.

728x90
반응형