|
| 1 | +package _2020_카카오_인턴십.P3; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.HashSet; |
| 6 | + |
| 7 | +public class Main { |
| 8 | + |
| 9 | + public static void main(String[] args) { |
| 10 | + Solution sol = new Solution(); |
| 11 | + System.out.println(Arrays.toString(sol.solution(new String[]{"DIA", "RUBY", "RUBY", "DIA", "DIA", "EMERALD", "SAPPHIRE", "DIA"}))); |
| 12 | + System.out.println(Arrays.toString(sol.solution(new String[]{"AA", "AB", "AC", "AA", "AC"}))); |
| 13 | + System.out.println(Arrays.toString(sol.solution(new String[]{"XYZ", "XYZ", "XYZ"}))); |
| 14 | + System.out.println(Arrays.toString(sol.solution(new String[]{"DIA", "EM", "EM", "RUB", "DIA"}))); // 3, 5 |
| 15 | + System.out.println(Arrays.toString(sol.solution(new String[]{"ZZZ", "YYY", "NNNN", "YYY", "BBB"}))); |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +class Solution { |
| 20 | + |
| 21 | + public int[] solution(String[] gems) { |
| 22 | + |
| 23 | + HashSet<String> set = new HashSet<>(Arrays.asList(gems)); |
| 24 | + int n = gems.length, size = set.size(); |
| 25 | + int ans_low = 0, ans_high = n-1; |
| 26 | + |
| 27 | + int low = 0, high = 0; |
| 28 | + HashMap<String, Integer> map = new HashMap<>(); |
| 29 | + map.put(gems[low], 1); |
| 30 | + while (low < n && high < n) { |
| 31 | + if (map.size() < size) { |
| 32 | + high ++; |
| 33 | + if (high < n) map.merge(gems[high], 1, Integer::sum); |
| 34 | + } else { |
| 35 | + if (map.size() == size && |
| 36 | + ((ans_high - ans_low) > (high - low) || low < ans_low)) { |
| 37 | + ans_low = low; |
| 38 | + ans_high = high; |
| 39 | + } |
| 40 | + if (map.get(gems[low]) != null) map.put(gems[low], map.get(gems[low])-1); |
| 41 | + if (map.get(gems[low]) == 0) map.remove(gems[low]); |
| 42 | + low ++; |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + return new int[]{ans_low+1, ans_high+1}; |
| 47 | + } |
| 48 | +} |
0 commit comments