- 👯 I majored in Electronic Engineering
- 📫 Konkuk University (2015.03 ~ 2021.08)
brandnew-one / coding_test Goto Github PK
View Code? Open in Web Editor NEW코테 스터디입니다
코테 스터디입니다
초기 풀이는 접두어
라는 문제조건을 제대로 파악하지 못하고 한 전화번호가 다른 전화번호에 포함이 되는지를 확인해서 오답을 받았다.
제발 문제를 똑바로 읽자!
그래서 아래와 같이 로직을 수정했다.
접두어
로 가지는지 확인bool cmp(string a, string b) {
if(a.size() >= b.size()) {
return false;
} else return true;
}
bool solution(vector<string> phone_book) {
bool answer = true;
sort(phone_book.begin(), phone_book.end(), cmp);
for(int i = 0; i < phone_book.size() - 1; i++) {
for(int j = i + 1; j < phone_book.size(); j++) {
// 전화번호 중복되지 않기 때문에 같은 길이는 비교할 필요x
if(phone_book[i].size() == phone_book[j].size())continue;
string temp = phone_book[j].substr(0, phone_book[i].size());
if(temp.find(phone_book[i]) != string::npos) {
return false;
}
}
}
return answer;
}
하지만 위와 같이 코드를 작성하면 시간초과를 받게된다. 전화번호부의 길이가 10^6
이기 때문에 위와 같이 O(N^2)
의 시간복잡도를 가지게 되면
최악의 경우 O(10^12)
로 시간초과가 발생할 수 밖에 없다.
사실 문제를 풀기전부터 O(N^2)으로는 시간초과가 날걸 예상했지만 마땅히 시간복잡도를 줄일 방법이 생각나지 않았기 때문에 최대한 꼼수를 부려서 길이가 같은 경우는 skip 할 수 있도록 설정했는데 역시나 시간초과였다 ㅠ
unordered_set<string> set;
bool solution(vector<string> phone_book) {
bool answer = true;
for(int i = 0; i < phone_book.size(); i++) {
set.insert(phone_book[i]);
}
for(int i = 0; i < phone_book.size(); i++) {
for(int j = 0; j <= phone_book[i].size() - 1; j++) {
string temp;
if(j == 0) temp = phone_book[i][0];
else {
temp = phone_book[i].substr(0, j);
}
if(set.find(temp) != set.end()) return false;
}
}
return answer;
}
위와 같이 set 을 이용해보자! ( set의 경우에는 insert, find, erase 의 시간복잡도가 O(1) )
1 ~ 해당전화번호 길이 - 1
까지 잘라서 set에 존재하는지 확인한다전화번호의 길이는 1이상 20 이하로 설정되어 있기 때문에 결국 최악의 경우에도 O(20 * N)으로 O(N)
의 시간복잡도가 보장된다.
해시 자료구조를 많이 사용해보지 않아서 풀이를 떠올리기가 되게 어려웠던 문제였다. 비슷한 예제들을 더 풀어보고 다시 정리해봐야 겠다.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.