hyelie
hyelie
Hyeil Jeong
       
글쓰기    관리    수식입력
  • 전체보기 (495)
    • PS (283)
      • Algorithm (28)
      • PS Log (244)
      • Contest (6)
      • Tips (5)
    • Development (52)
      • Java (14)
      • Spring (23)
      • SQL (2)
      • Node.js (2)
      • Socket.io (3)
      • Study (4)
      • Utils (4)
    • DevOps (36)
      • Git (5)
      • Docker (4)
      • Kubernetes (2)
      • GCP (3)
      • Environment Set Up (8)
      • Tutorial (12)
      • Figma (2)
    • CS (74)
      • OOP (7)
      • OS (24)
      • DB (2)
      • Network (24)
      • Architecture (0)
      • Security (2)
      • Software Design (0)
      • Parallel Computing (15)
    • Project (15)
      • Project N2T (5)
      • Project ASG (0)
      • Project Meerkat (1)
      • Model Checking (7)
      • Ideas (2)
    • 내가 하고싶은 것! (34)
      • Plan (16)
      • Software Maestro (10)
      • 취준 (8)
hELLO · Designed By 정상우.
hyelie

hyelie

PS/Algorithm

좌표 압축

 값의 대소 관계만 필요하다면 수를 바꾸어 사용할 수 있다.

 예를 들어 [0, 1, 5, 6, 11] 이런 좌표라면 [0, 1, 2, 3, 4]로 바꿀 수 있고, [0, 100, 150, 50, 175, 50, 50] 이런 좌표라면 [0, 2, 3, 1, 4, 1, 1]로 바꿀 수 있다.

 방법은 크게 2가지가 있다.

  • vector의 unique 값을 지우고 lower_bound로 해당 값을 찾는 방법
  • set으로 중복을 지우고 map으로 압축된 좌표를 mapping하는 방법

 

1. vector의 unique 값을 지우고 lower_bound로 찾는 방법 : O(nlogn)

void gridCompress(vector<int> &arr){
    vector<int> temp(arr.size());
    for(int i = 0; i<arr.size(); i++){
        temp[i] = arr[i];
    }
    sort(temp.begin(), temp.end());
    temp.erase(unique(temp.begin(), temp.end()), temp.end());
    for(int i = 0; i<arr.size(); i++){
    	arr[i] = lower_bound(temp.begin(), temp.end(), arr[i]) - temp.begin();
    }
}

 

2. set으로 중복을 지우고 map으로 값을 mapping하는 방법 : O(nlogn)

void gridCompress(vector<int> &arr){
	set<int> temp;
	for(int i = 0; i<arr.size(); i++){
		temp.insert(arr[i]);
	}

	int i = 0;
   	map<int, int> mapper;
	for(int elem : temp){
		mapper[elem] = i++;
	}

	for(int i = 0; i<arr.size(); i++){
    	arr[i] = mapper[arr[i]];
    }
}

 

 기억만 해 두고, 그때그때 좋은 것을 사용하자. 그러나 기본적으로는 위의 것이 더 빠르다!

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

누적 합 Prefix Sum  (0) 2022.07.10
동적 계획법 Dynamic Programming (+ LIS)  (0) 2022.07.09
정렬 ***TODO  (0) 2022.06.27
그래프 알고리즘 - (7) BST의 간단한 구현과 Tree traversal  (0) 2022.06.22
그래프 알고리즘 - (6) 위상 정렬 Topological sort  (0) 2022.06.22
    hyelie
    hyelie

    티스토리툴바