알고리즘/프로그래머스
[프로그래머스/c++] 숫자 짝꿍
녕이
2022. 12. 1. 11:59
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/131128#
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
X의 원소 개수를 세서 Y에 있는지 체크할 수 있다.
여기서 answer의 값이 비어있다면 -1, 0으로만 구성되어 있다면 0
num 배열에 넣어서 개수를 셀 수 있다.
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool zero(string str) {
for(auto s: str) if(s != '0') return false;
return true;
}
string solution(string X, string Y) {
string answer = "";
for(int i=0; i<X.size(); i++) num[X[i] - '0']++;
for(int i=0; i<Y.size(); i++) {
if(num[Y[i] - '0'] >= 1) {
answer += Y[i];
num[Y[i] - '0']--;
}
}
if(answer.size() == 0) return "-1";
if(zero(answer)) return "0";
sort(answer.begin(), answer.end(), greater<>());
return answer;
}
map으로도 할 수 있다.
#include <string>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
bool zero(string str) {
for(auto s: str) if(s != '0') return false;
return true;
}
string solution(string X, string Y) {
string answer = "";
map<char, int> m;
for(auto x: X) m[x]++;
for(auto y: Y) {
if(m[y] >= 1) {
answer += y;
m[y]--;
}
}
if(answer == "") return "-1";
if(zero(answer)) return "0";
sort(answer.begin(), answer.end(), greater<>());
return answer;
}
둘 중에 복잡도가 더 효율적인 것이 궁금해서 결과를 보니~ 역시 배열이 더 빠르다
728x90