algorithm/Algorithm-Core

좌표압축 알고리즘

아르비스 2018. 12. 8. 06:42
static int solution(int n, int[][] data) {

// 좌표 압축
ArrayList<Integer> xList = new ArrayList<>();
ArrayList<Integer> yList = new ArrayList<>();

for (int i = 0; i < n; i++) {

xList.add(data[i][0]);
yList.add(data[i][1]);
}

ArrayList<Integer> uniqueXList = new ArrayList<>(new HashSet<>(xList));
ArrayList<Integer> uniqueYList = new ArrayList<>(new HashSet<>(yList));

Collections.sort(uniqueXList);
Collections.sort(uniqueYList);

// 구간합 배열
int[][] S = new int[n][n];

for (int i = 0; i < n; i++) {

int x = uniqueXList.indexOf(new Integer(data[i][0]));
int y = uniqueYList.indexOf(new Integer(data[i][1]));

// 좌표 압축 적용
data[i][0] = x;
data[i][1] = y;

// 구간합 배열 초기값
S[x][y] = 1;
}

// N^2 구간합 구하기
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {

S[i][j] += (i - 1 >= 0 ? S[i - 1][j] : 0)
+ (j - 1 >= 0 ? S[i][j - 1] : 0)
- (i - 1 >= 0 && j - 1 >= 0 ? S[i - 1][j - 1] : 0);
}
}