본문 바로가기
SW/알고리즘 문제풀이

[Codility] Lesson6 - Sorting: Distinct

by 미래미래로 2020. 12. 22.
728x90

Problem

Write a function

int solution(vector<int> &A);

that, given an array A consisting of N integers, returns the number of distinct values in array A.

For example, given array A consisting of six elements such that:

A[0] = 2 A[1] = 1 A[2] = 1 A[3] = 2 A[4] = 3 A[5] = 1

the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 2 and 3.

Write an efficient algorithm for the following assumptions:

  • N is an integer within the range [0..100,000];
  • each element of array A is an integer within the range [−1,000,000..1,000,000].

    Copyright 2009–2020 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

How to solve

- 정보

N의 길이를 가진 배열 A

 

 

- 구해야 하는것?

벡터의 유니크한 원소의 갯수!

 

A vector의 unique 원소 구하는 방법!

sort(A.begin(), A.end());

A.erase(unique(A.begin(), A.end()), A.end());

 

Solution(c++)

// you can use includes, for example:
#include <bits/stdc++.h>

// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;

int solution(vector<int> &A) {
    // write your code in C++14 (g++ 6.2.0)
    sort(A.begin(), A.end());
    A.erase(unique(A.begin(), A.end()), A.end());
    int res = A.size();
    return res;
}

Test Result

 

728x90

댓글