Algorithm Study - 003

2021. 6. 3. 16:56·Algorithm/JAVA

Problem


https://app.codility.com/programmers/lessons/6-sorting/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].

배열의 중복제거이다. Set 인터페이스가 떠오르고 해당 인터페이스를 상속받는 HashSet과 TreeSet 구현 클래스가 떠오른다면 성공.

https://coding-factory.tistory.com/554

Solution


// 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) {

        if(A.length == 0) return 0;

        HashSet<Integer> set = new HashSet<>();

        for(int su : A){
            set.add(su);
        }

        return set.size();
    }
}

HashSet 클래스를 이용한 중복제거.

이후 해당 객체의 사이즈를 리턴하면 된다. 

 

Learn Point


1. 자료구조나 알고리즘 관련 문제는 특정 클래스를 안쓰고, 최대한 단순하게 해야한다는 강박관념이 생각을 앗아간 사례이다. ( 시간복잡도... )

'Algorithm > JAVA' 카테고리의 다른 글

Algorithm Study - 002  (0) 2021.06.02
Algorithm Study - 001  (0) 2021.06.02
숫자 반전 알고리즘  (0) 2021.06.02
'Algorithm/JAVA' 카테고리의 다른 글
  • Algorithm Study - 002
  • Algorithm Study - 001
  • 숫자 반전 알고리즘
seowooJeong
seowooJeong
  • seowooJeong
    개발일기
    seowooJeong
  • 전체
    오늘
    어제
    • 분류 전체보기 (25)
      • FrontEnd (6)
      • BackEnd (6)
      • Project (6)
      • Algorithm (4)
        • JAVA (4)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • React
    • Spring
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    QueryDSL 오류
    jeknins 파이프라인
    gitlab ci/cd
    resultmap 중첩
    jenkinsfile
    jenkinsfile 설정
    Java
    resultmap 리스트
    jenkins gitlab
    querydsl 환경설정
    숫자 알고리즘
    Spring QueryDsl
    jQuery
    숫자 반전
    mybatis list
    spring msa cicd
    build.gradle querydsl
    collection 리스트
    intellij querydsl
    숫자 거꾸로
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
seowooJeong
Algorithm Study - 003
상단으로

티스토리툴바