본문 바로가기

DEV/문제풀이

Lesson6 - Distinct

반응형

문제

Write a function

class Solution { public int solution(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].

 

코드

 

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// you can also use imports, for example:

import java.util.*;



// you can write to stdout for debugging purposes, e.g.

// System.out.println("this is a debug message");



class Solution {

    public int solution(int[] A) {

        // write your code in Java SE 8

        int res = 0;



	//오름차순 정렬

	Arrays.sort(A);



	for(int i=0;i < A.length;i++ ){

		if(i==0) {

			res++;

			continue;

		}

			

		if(A[i-1] != A[i]){

			res++;

		}

	}



	return(res);

    }

}

 

요약

* 주어진 배열의 숫자들의 개수를 카운팅하는 문제

정렬 후 앞배열값과 비교하여 다른 경우 카운트 하는 방법으로 해결

 

반응형

'DEV > 문제풀이' 카테고리의 다른 글

Lesson 2(Iterations) - OddOccurrencesInArray  (0) 2020.12.29
Codility  (0) 2020.12.26
Lesson 2(Iterations) - CyclicRotation  (0) 2020.12.25
Lesson 1(Iterations) - Binary Gap  (0) 2020.12.24
Lesson5 - MinAvgTwoSlice  (0) 2019.04.23
댓글