728x90
2215 - Find the Difference of Two Arrays


풀이
두 배열 nums1, nums2
- `answer[0]`: nums1에만 있고 nums2에는 없는 값들
- `answer[1]:` nums2에만 있고 nums1에는 없는 값들
-> 중복 없이(distinct) 반환 => `Set`
코드
class Solution {
public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
for (int n : nums1) set1.add(n);
for (int n : nums2) set2.add(n);
List<Integer> diff1 = new ArrayList<>();
List<Integer> diff2 = new ArrayList<>();
for (int s : set1) {
if (!set2.contains(s)) {
diff1.add(s);
}
}
for (int s : set2) {
if (!set1.contains(s)) {
diff2.add(s);
}
}
return Arrays.asList(diff1, diff2);
}
}
1207 - Unique Number of Occurrences

풀이
배열 arr에서 각 숫자의 등장 횟수(빈도) 구한 뒤 같은 빈도 2개 이상 있으면 false
=> 등장 횟수 모두 서로 달라야 함
코드
class Solution {
public boolean uniqueOccurrences(int[] arr) {
Map<Integer, Integer> HM = new HashMap<>();
for (int a : arr) {
HM.put(a, HM.getOrDefault(a, 0) + 1);
}
Set<Integer> set = new HashSet<>(HM.values());
return set.size() == HM.size();
}
}
1657 - Determine if Two String Are Close


풀이
- 문자 위치 바꾸기(swap): abcde -> aecdb
- 문자 전체 교환: aacabb -> bbcbaa
-> 두 문자열 close하려면 문자 종류 같음 + 문자 빈도 집합 같음
/ 리스트 추출 -> 정렬 후 비교
코드
class Solution {
public boolean closeStrings(String word1, String word2) {
if (word1.length() != word2.length()) return false;
Map<Character, Integer> map1 = new HashMap<>();
for (char c : word1.toCharArray()) {
map1.put(c, map1.getOrDefault(c, 0) + 1);
}
Map<Character, Integer> map2 = new HashMap<>();
for (char c : word2.toCharArray()) {
map2.put(c, map2.getOrDefault(c, 0) + 1);
}
if (!map1.keySet().equals(map2.keySet())) {
return false;
}
List<Integer> freq1 = new ArrayList<>(map1.values());
List<Integer> freq2 = new ArrayList<>(map2.values());
Collections.sort(freq1);
Collections.sort(freq2);
return freq1.equals(freq2);
}
}
2352 - Equal Row and Column Pairs


풀이
n x n 행렬 -> (ri, cj) 쌍 중 row i와 column j가 완전히 같은 배열인 경우 개수
ex. grid = [[3, 2, 1],[1, 7, 6],[2, 7, 7]]
-> Row 0: [3, 2, 1], Row 1: [1, 7, 6], Row 2: [2, 7, 7]
/ Column 0: [3, 1, 2], Column 1: [2, 7, 7], Column 2: [1, 6, 7]
-> Row 2 == Column 1 => 1개
각 행 문자열로 변환 후 key로 저장, 빈도 저장
-> 열(column)을 배열(`arr`)로 만든 뒤 그 배열과 동일한 행(row) 몇 개 있는지 `HM`에서 찾음
코드
class Solution {
public int equalPairs(int[][] grid) {
int n = grid.length;
Map<String, Integer> HM = new HashMap<>();
for (int[] g : grid) {
String key = Arrays.toString(g);
HM.put(key, HM.getOrDefault(key, 0) + 1);
}
int cnt = 0;
for (int col = 0; col < n; col++) {
int[] arr = new int[n];
for (int row = 0; row < n; row++) {
arr[row] = grid[row][col];
}
String key = Arrays.toString(arr);
cnt += HM.getOrDefault(key, 0);
}
return cnt;
}
}
출처
LeetCode 75 - Study Plan - LeetCode
Ace Coding Interview with 75 Qs
leetcode.com
728x90
반응형