|
| 1 | +package leetcode.easy; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * https://leetcode.com/problems/intersection-of-multiple-arrays/description/ |
| 7 | + * <p> |
| 8 | + * Example 1: |
| 9 | + * Input: nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]] |
| 10 | + * Output: [3,4] |
| 11 | + * Explanation: |
| 12 | + * The only integers present in each of nums[0] = [3,1,2,4,5], nums[1] = [1,2,3,4], and nums[2] = [3,4,5,6] are 3 and 4, so we return [3,4]. |
| 13 | + * <p> |
| 14 | + * Example 2: |
| 15 | + * Input: nums = [[1,2,3],[4,5,6]] |
| 16 | + * Output: [] |
| 17 | + * Explanation: |
| 18 | + * There does not exist any integer present both in nums[0] and nums[1], so we return an empty list []. |
| 19 | + */ |
| 20 | +public class IntersectionOfMultipleArrays { |
| 21 | + public static void main(String[] args) { |
| 22 | + |
| 23 | + // Test case 1 |
| 24 | + int[][] nums1 = { |
| 25 | + {3, 1, 2, 4, 5}, |
| 26 | + {1, 2, 3, 4}, |
| 27 | + {3, 4, 5, 6} |
| 28 | + }; |
| 29 | + List<Integer> result1 = intersection(nums1); |
| 30 | + System.out.println("Intersection of nums1: " + result1); |
| 31 | + |
| 32 | + // Test case 2 |
| 33 | + int[][] nums2 = { |
| 34 | + {1, 2, 3}, |
| 35 | + {4, 5, 6} |
| 36 | + }; |
| 37 | + List<Integer> result2 = intersection(nums2); |
| 38 | + System.out.println("Intersection of nums2: " + result2); |
| 39 | + } |
| 40 | + |
| 41 | + public static List<Integer> intersection(int[][] nums) { |
| 42 | + // Initialize a HashSet with the elements of the first array |
| 43 | + Set<Integer> resultSet = new HashSet<>(); |
| 44 | + for (int num : nums[0]) { |
| 45 | + resultSet.add(num); |
| 46 | + } |
| 47 | + |
| 48 | + // Iterate through the rest of the arrays and keep only the common elements |
| 49 | + for (int i = 1; i < nums.length; i++) { |
| 50 | + Set<Integer> currentSet = new HashSet<>(); |
| 51 | + for (int num : nums[i]) { |
| 52 | + if (resultSet.contains(num)) { |
| 53 | + currentSet.add(num); |
| 54 | + } |
| 55 | + } |
| 56 | + resultSet = currentSet; // Update the result set to only contain common elements |
| 57 | + } |
| 58 | + |
| 59 | + // Convert the result set to a list, sort it, and return it |
| 60 | + List<Integer> resultList = new ArrayList<>(resultSet); |
| 61 | + Collections.sort(resultList); // Sort the result in ascending order |
| 62 | + return resultList; |
| 63 | + } |
| 64 | + |
| 65 | + |
| 66 | +} |
0 commit comments