매일 Algorithm

신재원·2023년 2월 20일
0

Algorithm

목록 보기
43/243

프로그래머스 (LEVEL 1, 해시)

import java.util.*;
class Solution {
    public int solution(int[] nums) {
        int n = nums.length/2;

        // set 컬렉션을 사용해 중복 제거
        // HashSet, TreeSet이 있지만 HashSet이 처리 속도가 빠르다.
        // (TreeSet은 다양한 정렬 기능제공) (add와 동시에 정렬이됨)
        Set<Integer> set = new HashSet<>();

        for(int num : nums){
            set.add(num);
        }
        if(n < set.size()){
            return n;
        }


        return set.size();
    }
}

프로그래머스 (LEVEV 1, 해시)

import java.util.*;

public class problem104 {
    class Solution {
        public String solution(String[] participant, String[] completion) {

            // "leo", "kiki" "eden" 을 B C A라고 생각하고 오름차순 정렬
            // 완주하지 못한사람은 무조건 한명임
            Arrays.sort(participant);
            Arrays.sort(completion);

            for(int i = 0 ; i < completion.length; i++){
                if(participant[i].equals(completion[i])){
                    // 배열에서 일치하지 않는 마지막 배열이 남게된다.
                    // 그 사람이 완주자 명단에 없는사람이다.
                    continue;
                }
                else{
                    // 동일한 이름의 참가자 있을수 있음.
                    return participant[i];
                }

            }


            return participant[participant.length-1];
        }
    }
}


/* 
List는 중복검증후 중복된 값의 반환이 안되는것같다.
class Solution {
    public String solution(String[] participant, String[] completion) {
        String answer = "";
        List<String> pList = new ArrayList<>();
        for(String p : participant){
            pList.add(p);
        }

        List<String> cList = new ArrayList<>();
        for(String c : completion){
            pList.add(c);
        }
        Collections.sort(pList);
        Collections.sort(cList);

        for(int i = 0 ; i < cList.size(); i++){
            if(pList.get(i).equals(cList.get(i))){
                continue;
            }else{
                return pList.get(i);
            }
        }


        return pList.get(pList.size()-1);
    }
}
*/

프로그래머스 (LEVEL 2, 해시)

import java.util.*;
class Solution {
    public boolean solution(String[] phone_book) {
        boolean answer = true;
        
        // 같은 전화번호가 중복되지 않음
        Set <String> set = new HashSet<>();
        
        // 119 97674223 119552441
        for(String a : phone_book){
            set.add(a);
        }
        
        for(String p : phone_book){
            for(int i = 0 ; i < p.length(); i++){
            // set을 순회하며 번호를 포함 하고 있는지 확인
            if(set.contains(p.substring(0,i))){
                return false;
            }         
            }
        }
        return answer;
    }
}

0개의 댓글