diff --git "a/leetcode3/\352\263\275\355\230\204\354\247\200/15. 3Sum" "b/leetcode3/\352\263\275\355\230\204\354\247\200/15. 3Sum" new file mode 100644 index 00000000..25f8495a --- /dev/null +++ "b/leetcode3/\352\263\275\355\230\204\354\247\200/15. 3Sum" @@ -0,0 +1,47 @@ +[문제내용] +Example 1: + +Input: nums = [-1,0,1,2,-1,-4] +Output: [[-1,-1,2],[-1,0,1]] +Explanation: +nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. +nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. +nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. +The distinct triplets are [-1,0,1] and [-1,-1,2]. +Notice that the order of the output and the order of the triplets does not matter. +Example 2: + +Input: nums = [0,1,1] +Output: [] +Explanation: The only possible triplet does not sum up to 0. +Example 3: + +Input: nums = [0,0,0] +Output: [[0,0,0]] +Explanation: The only possible triplet sums up to 0. + + +[작성한 답안] +class Solution { + public List> threeSum(int[] nums) { + List> result = new ArrayList<>(); + + Arrays.sort(nums); + + for (int i = 0; i < nums.length - 2; i++) { + int left = i + 1; + int right = nums.length - 1; + + while (left < right) { + int sum = nums[i] + nums[left] + nums[right]; + + // 세 수의 합이 0일 때 출력 + if (sum == 0) { + result.add(Arrays.sort(nums[i], nums[left], nums[right])); + } else { + break; + } + } + } + } +} diff --git "a/leetcode3/\352\263\275\355\230\204\354\247\200/49. Group Anagrams" "b/leetcode3/\352\263\275\355\230\204\354\247\200/49. Group Anagrams" new file mode 100644 index 00000000..e54a5d87 --- /dev/null +++ "b/leetcode3/\352\263\275\355\230\204\354\247\200/49. Group Anagrams" @@ -0,0 +1,42 @@ +[문제내용] +Example 1: + +Input: strs = ["eat","tea","tan","ate","nat","bat"] + +Output: [["bat"],["nat","tan"],["ate","eat","tea"]] + +Explanation: + +There is no string in strs that can be rearranged to form "bat". +The strings "nat" and "tan" are anagrams as they can be rearranged to form each other. +The strings "ate", "eat", and "tea" are anagrams as they can be rearranged to form each other. +Example 2: + +Input: strs = [""] + +Output: [[""]] + +Example 3: + +Input: strs = ["a"] + +Output: [["a"]] + + +[작성한 코드답안] +class Solution { + public List> groupAnagrams(String[] strs) { + Map> answer = new HashMap<>(); + for(String str : strs) { + // 문자 나열 + char[] c = str.toCharArray(); + Arrays.sort(c); // 나열한 문자 정렬 + String s = String.valueOf(c); + + if(!answer.containsKey(s)) + answer.put(s, new ArrayList<>()); + answer.get(s).add(str); + } + return new ArrayList<>(answer.values()); + } +}