
Sponsored
Sponsored
This approach involves iterating through the given table and using a hash map (or dictionary) to count how many times each actor-director pair appears. After counting, you can filter these pairs to only include those that have a count of three or more.
Time Complexity: O(n), where n is the number of entries in the table.
Space Complexity: O(m), where m is the number of distinct actor-director pairs.
1import java.util.*;
2
3public class Solution {
4 public static void main(String[] args) {
5 int[][] actorDirector = {
6 {1, 1}, {1, 1}, {1, 1},
7 {1, 2}, {1, 2},
8 {2, 1}, {2, 1}
9 };
10
11 Map<List<Integer>, Integer> pairCount = new HashMap<>();
12 for (int[] pair : actorDirector) {
13 List<Integer> list = Arrays.asList(pair[0], pair[1]);
14 pairCount.put(list, pairCount.getOrDefault(list, 0) + 1);
15 }
16
17 System.out.println("+-------------+-------------+");
18 System.out.println("| actor_id | director_id |");
19 System.out.println("+-------------+-------------+");
20 for (Map.Entry<List<Integer>, Integer> entry : pairCount.entrySet()) {
21 if (entry.getValue() >= 3) {
22 System.out.printf("| %11d | %11d |\n", entry.getKey().get(0), entry.getKey().get(1));
23 }
24 }
25 }
26}This Java solution employs a HashMap where the key is a list of integers representing a pair, and the value is the count of occurrences. As we iterate through the array, we update the count in the map and then output pairs with a count of three or more.
If this were a SQL-based system, an efficient way to find the actors and directors who have cooperated at least three times is by using SQL's GROUP BY and HAVING clauses. The GROUP BY clause allows us to group rows that have the same values in specified columns, while the HAVING clause will filter these groups based on a given condition.
Time Complexity: O(n log n), due to potential sorting in the GROUP BY operation.
Space Complexity: O(k), where k is the number of groups formed from distinct pairs of actors and directors.
1SELECT actor_id, director_id
2FROM ActorDirector
3GROUP BY actor_id,In this SQL solution, we group the entries in the ActorDirector table by actor_id and director_id. The HAVING clause ensures that only pairs with three or more entries in the table are selected for the final result.