관리 메뉴

Mini

배열 조회는 O(1)을 활용하라 => visit 배열사용 본문

Algorithm/개념

배열 조회는 O(1)을 활용하라 => visit 배열사용

Mini_96 2023. 8. 13. 21:36

* 기존 : 2중for 문 : O(N^2)

* visit배열이용 : O(N)

ex) 77 이면 이전에 23이 나왔었는지만 확인하면됨.

반복문 돌면서 visit에 기록

#include <bits/stdc++.h>
using namespace std;

int v[100];
int func1(int N) {
    return -1;
}

int func2(int arr[], int N) {
    for (int i = 0; i < N; ++i) {
        if (v[100-arr[i]]) {
            return 1;
        }
        else {
            v[arr[i]] = 1;
        }
    }
    return 0;
}

int func3(int N) {
    return -1;
}

int func4(int N) {
    return -1;
}

void test1() {
    cout << "****** func1 test ******\n";
    int n[3] = { 16, 34567, 27639 };
    int ans[3] = { 60, 278812814, 178254968 };
    for (int i = 0; i < 3; i++) {
        int result = func1(n[i]);
        cout << "TC #" << i << '\n';
        cout << "expected : " << ans[i] << " result : " << result;
        if (ans[i] == result) cout << " ... Correct!\n";
        else cout << " ... Wrong!\n";
    }
    cout << "*************************\n\n";
}

void test2() {
    cout << "****** func2 test ******\n";
    int arr[3][4] = { {1,52,48}, {50,42}, {4,13,63,87} };
    int n[3] = { 3, 2, 4 };
    int ans[3] = { 1, 0, 1 };
    for (int i = 0; i < 3; i++) {
        int result = func2(arr[i], n[i]);
        cout << "TC #" << i << '\n';
        cout << "expected : " << ans[i] << " result : " << result;
        if (ans[i] == result) cout << " ... Correct!\n";
        else cout << " ... Wrong!\n";
    }
    cout << "*************************\n\n";
}

void test3() {
    cout << "****** func3 test ******\n";
    int n[3] = { 9, 693953651, 756580036 };
    int ans[3] = { 1, 0, 1 };
    for (int i = 0; i < 3; i++) {
        int result = func3(n[i]);
        cout << "TC #" << i << '\n';
        cout << "expected : " << ans[i] << " result : " << result;
        if (ans[i] == result) cout << " ... Correct!\n";
        else cout << " ... Wrong!\n";
    }
    cout << "*************************\n\n";
}

void test4() {
    cout << "****** func4 test ******\n";
    int n[3] = { 5, 97615282, 1024 };
    int ans[3] = { 4, 67108864, 1024 };
    for (int i = 0; i < 3; i++) {
        int result = func4(n[i]);
        cout << "TC #" << i << '\n';
        cout << "expected : " << ans[i] << " result : " << result;
        if (ans[i] == result) cout << " ... Correct!\n";
        else cout << " ... Wrong!\n";
    }
    cout << "*************************\n\n";
}

int main(void) {
    test1();
    test2();
    test3();
    test4();
}

 

-출처 : https://www.youtube.com/watch?v=mBeyFsHqzHg&list=PLtqbFd2VIQv4O6D6l9HcD732hdrnYb6CY&index=4 

 

'Algorithm > 개념' 카테고리의 다른 글

배열 insert, erase 구현 cpp  (0) 2023.08.13
순열 vs 중복순열 vs 조합 vs 중복조합 종결  (0) 2023.06.28