[Codility] Lesson 15 - AbsDistinct

개발자·2021년 9월 4일

Task discription

A non-empty array A consisting of N numbers is given. The array is sorted in non-decreasing order. The absolute distinct count of this array is the number of distinct absolute values among the elements of the array.

For example, consider array A such that:

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

The absolute distinct count of this array is 5, because there are 5 distinct absolute values among the elements of this array, namely 0, 1, 3, 5 and 6.

Write a function:

class Solution { public int solution(int[] A); }

that, given a non-empty array A consisting of N numbers, returns absolute distinct count of array A.

For example, given array A such that:

A[0] = -5
A[1] = -3
A[2] = -1
A[3] = 0
A[4] = 3
A[5] = 6
the function should return 5, as explained above.

Write an efficient algorithm for the following assumptions:

  • N is an integer within the range [1..100,000];
  • each element of array A is an integer within the range [−2,147,483,648..2,147,483,647];
    array A is sorted in non-decreasing order.

Source code

C++

#include <algorithm>

int solution(vector<int> &A) {
    int n = A.size();
    vector<int> tmp;
    for(int i=0;i<n;i++) {
        tmp.push_back(abs(A[i]));
    }
    sort(tmp.begin(), tmp.end());
    tmp.erase(unique(tmp.begin(), tmp.end()), tmp.end());
    return tmp.size();
}

java

import java.util.*;

class Solution {
    public int solution(int[] A) {
        int n = A.length;
        ArrayList<Integer> tmp = new ArrayList<Integer>();
        for(int i=0;i<n;i++) {
            tmp.add(Math.abs(A[i]));
        }
        HashSet<Integer> ans = new HashSet<Integer>(tmp);
        return ans.size();
    }
}
profile
log.info("공부 기록 블로9")

0개의 댓글