https://school.programmers.co.kr/learn/courses/30/lessons/152996
๋ด ํ์ด
1. ์ด์ค for๋ฌธ
์๊ฐ ์ด๊ณผ๋ ์๋์ง๋ง ์คํ์๊ฐ์ด ์ค๋ ๊ฑธ๋ฆฐ๋ค.
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
long long solution(vector<int> weights) {
long long answer = 0;
// ์ค๋ฆ์ฐจ์ ์ ๋ ฌ
sort(weights.begin(), weights.end());
int same_count = 0;
for(int i = 0; i < weights.size()-1; ++i)
{
int left = weights[i];
for(int j = i+1; j < weights.size(); ++j)
{
int right = weights[j];
if( left == right
|| left*2 == right
|| left*3 == right*2
|| left*4 == right*3)
{
++answer;
}
}
}
return answer;
}
2. map
map์ key์ value ๋ฅผ long long ํ์ ์ผ๋ก ํด์ค์ผ ํ๋ค.
#include <string>
#include <vector>
#include <map>
using namespace std;
long long solution(vector<int> weights) {
long long answer = 0;
map<long long, long long> weight_map;
for(const auto& w : weights)
{
++weight_map[w];
}
for(const auto& w : weight_map)
{
answer += (w.second * (w.second-1))/2;
if(weight_map.end() != weight_map.find(w.first * 2))
answer += weight_map[w.first * 2] * w.second;
if(0 == w.first % 2 && weight_map.end() != weight_map.find(w.first / 2 * 3))
answer += weight_map[w.first / 2 * 3] * w.second;
if(0 == w.first % 3 && weight_map.end() != weight_map.find(w.first / 3 * 4))
answer += weight_map[w.first / 3 * 4] * w.second;
}
return answer;
}
'๐ฅ๏ธ Study Note > Coding Test' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ๋ก๊ทธ๋๋จธ์ค]level.2 - ํธํ ๋์ค(C++) (0) | 2023.06.18 |
---|---|
[ํ๋ก๊ทธ๋๋จธ์ค]level.2 - ์์ด ๋๋ง์๊ธฐ(C++) (0) | 2023.06.18 |
[ํ๋ก๊ทธ๋๋จธ์ค]level.1 - ํธ๋ํฐ ๋ฒํธ ๊ฐ๋ฆฌ๊ธฐ(C++) (0) | 2023.06.11 |
[ํ๋ก๊ทธ๋๋จธ์ค]level.2 - ์ฐ์๋ ๋ถ๋ถ ์์ด์ ํฉ(C++) (0) | 2023.06.10 |
[ํ๋ก๊ทธ๋๋จธ์ค] level.2 - ์กฐ์ด์คํฑ(C++) (1) | 2023.06.10 |