๐Ÿ“ Coding Test Study/C++

[10์ฃผ ์™„์„ฑ C++ ์ฝ”๋”ฉํ…Œ์ŠคํŠธ] ํ•„์ˆ˜๊ฐœ๋… - map, unique()

ibelieveinme 2023. 8. 6. 09:15
728x90

์ฝ”๋”ฉํ…Œ์ŠคํŠธ์—์„œ ์ค‘๋ณต์—†๋Š” ๊ฐ’์„ ์ถœ๋ ฅํ•˜๋ผ๊ณ  ํ•  ๋•Œ, map ์ด๋‚˜ unique ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•œ๋‹ค.

 

1. map

#include <iostream>
#include <map>
#include <vector>
using namespace std;

map<int, int> mp;

int main() {
	vector<int> v{ 1,1,2,2,3,3 };
	for (int i : v) {
		if (mp[i]) continue;
		else mp[i] = 1;
	}
	vector<int> ret;
	for (auto it : mp) {
		ret.push_back(it.first);
	}
	for (int i : ret) cout << i << '\n';
}

 

2. unique()

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<int> v;

int main() {
	for (int i = 1; i <= 5; i++){
		v.push_back(i);
		v.push_back(i);
	}
	for (int i : v) cout << i << " ";
	cout << '\n';

	// ์ค‘๋ณต๋˜์ง€ ์•Š์€ ์š”์†Œ๋กœ ์ฑ„์šด ํ›„, ๊ทธ ๋‹ค์Œ ์ดํ„ฐ๋ ˆ์ดํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
	auto it = unique(v.begin(), v.end());
	cout << it - v.begin() << '\n';

	// ์•ž์—์„œ ๋ถ€ํ„ฐ ์ค‘๋ณต๋˜์ง€ ์•Š๊ฒŒ ์ฑ„์šด ํ›„ ๋‚˜๋จธ์ง€ ์š”์†Œ๋“ค์€ ๊ทธ๋Œ€๋กœ ๋‘”๋‹ค.
	for (int i : v) cout << i << " ";
	cout << '\n';

	//unique()์˜ iterator์—์„œ ๋ฒกํ„ฐ ๋๊นŒ์ง€๋ฅผ erase()๋กœ ์ง€์›Œ์ฃผ๋ฉด ๋œ๋‹ค.
	v.erase(it, v.end());
	for (int i : v) cout << i << " ";
	cout << '\n';

	return 0;
}

1 1 2 2 3 3 4 4 5 5
5
1 2 3 4 5 3 4 4 5 5
1 2 3 4 5

 

* unique(): ๋ฒ”์œ„ ์•ˆ์— ์š”์†Œ ์ค‘ ์—ฐ์†๋œ ์š”์†Œ๋ฅผ ์ง€์šฐ๊ณ  ๋‚˜๋จธ์ง€ ์š”์†Œ๋“ค์€ ์‚ญ์ œํ•˜์ง€ ์•Š๊ณ  ๊ทธ๋Œ€๋กœ ๋‘๋Š” ํ•จ์ˆ˜.

                   O(n)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ๊ฐ€์ง.

 

์ฆ‰, unique() ๋กœ ์ค‘๋ณต๋œ ์š”์†Œ๋ฅผ ์ฐพ์•„์„œ ์ •๋ ฌํ•˜๊ณ  ์ฐพ์€๊ณณ ๋’ค๋ถ€ํ„ฐ ๋๊นŒ์ง€๋ฅผ erase() ํ•˜๋ฉด ์ค‘๋ณต๋œ ์š”์†Œ๊ฐ€ ์ œ๊ฑฐ๋œ๋‹ค.

์ด ๋•Œ, ๋‚˜๋จธ์ง€ ์š”์†Œ๋“ค์€ ์‚ญ์ œํ•˜์ง€ ์•Š๊ณ  ๊ทธ๋Œ€๋กœ ๋‘๊ธฐ ๋•Œ๋ฌธ์— sort() ๋ฅผ ๋จผ์ € ํ•˜๊ณ  ํ•˜๋ฉด ์ค‘๋ณต๋œ ์ˆ˜๋ฅผ ๋ชจ๋‘ ์ œ๊ฑฐํ•œ ๋ฐฐ์—ด์ด ๋‚˜์˜จ๋‹ค.


* hash map ์ฐธ๊ณ  ๋ฌธ์ œ ๋ฐ ํ™œ์šฉ์˜ˆ์‹œ

https://i-believe-in-me.tistory.com/224

 

[C++][Programmers][ํ•ด์‹œ] ํฌ์ผ“๋ชฌ

https://school.programmers.co.kr/learn/courses/30/lessons/1845 ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š”

i-believe-in-me.tistory.com

ํฌ์ผ“๋ชฌ์„ 2/n ๊ฐœ ์„ ํƒํ–ˆ์„ ๋•Œ, ์„ ํƒํ•  ์ˆ˜ ์žˆ๋Š” ํฌ์ผ“๋ชฌ ์ข…๋ฅ˜์˜ ์ตœ๋Œ€๊ฐ’์„ ๊ตฌํ•ด์•ผ ํ•˜๋ฏ€๋กœ ํฌ์ผ“๋ชฌ ์ข…๋ฅ˜๋ณ„๋กœ count ํ•  hash map์ด ํ•„์š”ํ•˜๋‹ค.

 

* unique(), erase() ์ฐธ๊ณ  ๋ฌธ์ œ ๋ฐ ํ™œ์šฉ์˜ˆ์‹œ

https://i-believe-in-me.tistory.com/229

 

[C++][Programmers][์Šคํƒ/ํ] ๊ฐ™์€ ์ˆซ์ž๋Š” ์‹ซ์–ด

*๋ฌธ์ œ https://school.programmers.co.kr/learn/courses/30/lessons/12906 ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด

i-believe-in-me.tistory.com

๋‹จ์ˆœํžˆ ์—ฐ์†๋œ ์ˆซ์ž๋ฅผ ์ง€์šฐ๋ฉด ๋˜๋Š” ๋ฌธ์ œ์ด๋ฏ€๋กœ unique(), erase() ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜๋ฉด ๋œ๋‹ค.

728x90