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
'SW > 알고리즘 문제풀이' 카테고리의 다른 글
[Codility] Lesson7 - Stacks and Queues: Fish (0) | 2020.12.28 |
---|---|
[Codility] Lesson6 - Sorting: Max Product of Three (1) | 2020.12.23 |
[Codility] Lesson5 - Prefix Sums: Genomic Range Query (0) | 2020.12.21 |
[Codility] Lesson5 - Prefix Sums : Count Div (0) | 2020.12.21 |
[Codility] Lesson4 - Counting Elements : Missing Integer (c++) (0) | 2020.12.20 |
댓글