2019년 4월 13일 토요일

# 코딜리티 -> 주어진 배열에서 숫자별로 그룹핑하기.

Write a function

int solution(int A[], int N);

that, given a zero-indexed array A consisting of N integers, returns the number of distinct values in array A.

Assume that:

  • 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].

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
int solution(vector<int> &A) {
 if (A.size() == 0) return 0;

 sort(A.begin(), A.end());
 int answer = 0;
 int prevNum = 0;
 int curNum = A[0];
 for (int i = 1; i < A.size(); i++) {
  prevNum = A[i];
  if (curNum != prevNum) {
   answer++;
   curNum = A[i];
  }
 }

 return ++answer;
}

댓글 없음:

댓글 쓰기