Code Monkey home page Code Monkey logo

coding_test's Introduction

Sangwon Shin 👋

Hits

who am I?

  • 👯 I majored in Electronic Engineering
  • 📫 Konkuk University (2015.03 ~ 2021.08)

sangwon's github stats

sangwon's github stats

coding_test's People

Contributors

brandnew-one avatar seohyun-back avatar

Stargazers

 avatar

Watchers

 avatar

Forkers

seohyun-back

coding_test's Issues

[programmers]전화번호 목록

초기 풀이는 접두어 라는 문제조건을 제대로 파악하지 못하고 한 전화번호가 다른 전화번호에 포함이 되는지를 확인해서 오답을 받았다.
제발 문제를 똑바로 읽자!

그래서 아래와 같이 로직을 수정했다.

  • 전화번호의 길이를 기준으로 오름차순 정렬
  • 현재 확인하고 있는 번호보다 길이가 긴 전화번호 중 해당번호를 접두어로 가지는지 확인
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) )

  • 우선 set에 모든 전화번호를 넣는다
  • 그리고 각각의 전화번호를 1 ~ 해당전화번호 길이 - 1 까지 잘라서 set에 존재하는지 확인한다

전화번호의 길이는 1이상 20 이하로 설정되어 있기 때문에 결국 최악의 경우에도 O(20 * N)으로 O(N) 의 시간복잡도가 보장된다.

해시 자료구조를 많이 사용해보지 않아서 풀이를 떠올리기가 되게 어려웠던 문제였다. 비슷한 예제들을 더 풀어보고 다시 정리해봐야 겠다.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.