Brute-force : 무차별 대입

가능한 경우의 수를 모두 찾아서 답을 찾는 알고리즘

컴퓨터의 빠른 계산 속도를 이용하는 방법

 

완전탐색 방법

1. Brute Force : for문과 if문을 이용해 처음부터 끝까지 탐색하는 방법

2. 비트마스크

3. 순열

4. 백트래킹

5. BFS

6. DFS

7. 재귀함수

 

관련문제

재귀, 순열

  - 프로그래머스 완전탐색 소수찾기 programmers.co.kr/learn/courses/30/lessons/42839

중첩 for문, 재귀

  - https://www.acmicpc.net/problem/2309 백준 일곱 난쟁이
  - https://www.acmicpc.net/problem/7568 백준 덩치
  - https://www.acmicpc.net/problem/6603 백준 로또
  - https://www.acmicpc.net/problem/1065 백준 한수
  - https://www.acmicpc.net/problem/1107 백준 리모컨

 

1. 선언

1
2
3
4
5
6
7
import java.util.PriorityQueue; //import
 
//int형 priorityQueue 선언 (최소힙)
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
 
//int형 priorityQueue 선언 (최대힙)
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(Collections.reverseOrder());
cs

2. 값 추가

1
priorityQueue.offer(3);
cs

3. 값 삭제

1
priorityQueue.poll(); // priorityQueue에 첫번째 값을 반환하고 제거 비어있다면 null
cs

4. 값 출력

1
priorityQueue.peek(); //Priority Queue에서 우선순위가 가장 높은 값 출력
cs

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

[완전탐색] 완전탐색이란  (0) 2020.11.24
[힙(Hesp)] 더 맵게 JAVA  (0) 2020.11.10
[해시] HashMap 자주 쓰는 함수 정리  (0) 2020.11.08
[해시] 완주하지 못한 선수 JAVA  (0) 2020.11.08

처음에 배열로 시도를 했으나 효율성 테스트에서 통과하지 못하고

PriorityQueue를 사용해서 통과했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.*;
 
class Solution {
    public int solution(int[] scoville, int K) {
        int count = 0//섞은 횟수
        PriorityQueue<Integer> minHeap = new PriorityQueue<>(); //최소힙
        
        for(int s : scoville) {
            minHeap.offer(s);
        }
        
        while(minHeap.peek() < K) {
            if(minHeap.size() < 2) { //스코빌 지수가 K보다 작은데 원소가 하나일 경우
                return -1;
            }
            count++;
            minHeap.offer(minHeap.poll() + (minHeap.poll() * 2));
        }
       
        return count;
    }
    
}
cs

 

1. HashMap

Map의 한 종류로 <Key,Value>로 이루어진다.
Key값은 중복 불가능, Value는 중복 가능
순서는 유지되지 않음
해싱 검색으로 대용량 데이터 관리에 좋은 성능을 가진다.

2. 생성

1
2
import java.util.HashMap;
Map<String, Integer> hashMap = new HashMap<String, Integer>();
cs

3. Put(key, value)

1
2
3
hashMap.put("KEY1"1);
hashMap.put("KEY2"2);
hashMap.put("KEY3"1);
cs

4. remove(key)

1
hashMap.remove("KEY1");
cs

5. size()

HashMap에 저장된 엘리먼트의 개수를 반환

6. isEmpty()

컬렉션에서 엘리먼트의 유물 체크

7. values()

hashMap에 저장된 value 값을 Collection 형태로 출력

1
2
3
4
Collection<int> values = hashMap.values();
for (int value : values) {
    System.out.println(value);
}
cs

8. get(Key)

key값에 대한 엘리먼트를 가져온다.

9. clear()

hashMap에 있던 모든 값 사라진다.

10. containesKey(Key)

hashMap에 해당 key값이 포함되어 있는지 체크한다.
true, false return

11. containesValue(value)

hashMap에 해당 value값이 포함되어 있는지 체크한다.
true, false return

12. getOrDefault()

찾는 key값이 존대한다면 key의 value를 반환하고, 없다면 기본 값을 반환한다.

1
2
3
4
5
HashMap<> map = new HashMap<>();
 
map.getOrDefault("key""value");
System.out.println(map.get("key"))
> "value"
cs

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

[완전탐색] 완전탐색이란  (0) 2020.11.24
[힙(Heap)] 우선순위 큐(PriorityQueue)  (0) 2020.11.10
[힙(Hesp)] 더 맵게 JAVA  (0) 2020.11.10
[해시] 완주하지 못한 선수 JAVA  (0) 2020.11.08
  1. 처음 내가 푼 코드
    completion의 길이는 participant의 길이보다 1 작다는 정보를 이용하여 for문에서 비교
    Arrays.sort() 메소드를 이용하여 정렬을 하고 나면 시간이 오래 걸릴거라는 걱정이 있었지만 통과했다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.*;
 
class Solution {
    public String solution(String[] participant, String[] completion) {
        String answer = "";
 
        Arrays.sort(participant);
        Arrays.sort(completion);
 
        for(int i = 0; i < completion.length; i++) {
            if(!completion[i].equals(participant[i])) {
                return participant[i];
            }
        }
 
        return participant[participant.length-1];
    }
}
 
cs
 

 

 

 

 

  1. 해시맵 이용
    정확성과 효율성이 더 뛰어나다
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
import java.util.*;
 
class Solution {
    public String solution(String[] participant, String[] completion) {
        String answer = "";
 
        Map<String, Integer> hashMap = new HashMap<>();
 
        for(String player : participant) {
            hashMap.put(player, hashMap.getOrDefault(player, 0+ 1);
        }
 
        for(String player : completion) {
            hashMap.put(player, hashMap.get(player) - 1);
        }
 
        for(String key : hashMap.keySet()) {
            if(hashMap.get(key) != 0) {
                answer = key;
                break;
            }
        }
 
        return answer;
    }
}
cs

 

 

+ Recent posts