简体   繁体   中英

Minimizing time complexity when looping over two arrays

For a intro computer science class we have to write a function that finds the intersection of two arrays, which each unique element only being shown once and without allocating more space than we need.

For example:

array A = {1, 2, 3, 3, 3, 5}

array B = {2, 2, 2, 3, 5, 6}

intersection of A and B = {2, 3, 5}

How can I accomplish this without looping over the both arrays twice? As it stands I have:

//find how large of an array I'll need
for array A 
  for array A
    if A[i] is already somewhere earlier in array A
      stop
    else 
      loop through array B 
      if A[i] is in array B, increment a counter


declare a new array of size counter  

//add unique elements to the array
for array A 
  for array A
    if A[i] is already somewhere earlier in array A
      stop
    else 
      loop through array B 
      if A[i] is in array B, add it to the new array

It seems like this would be really inefficient I have two nearly identical nested for loops. If I was using python I could just append unique elements to list, but is there a way I could do something similar in C? I could just declare an array of the maximum size I could need, but I'm trying to minimize the space complexity.

If your are aware of sets you can use that. The time-complexity will be O(n)

You can know more about set and how to implement one in C here .

Then you can do something like this (written in Java):

public int[] intersection(int[] nums1, int[] nums2) {
    Set<Integer> set1 = getSet(nums1);
    Set<Integer> set2 = getSet(nums2);

    Set<Integer> ans = new HashSet<>();

    for(Integer i: set1) {
        if(set2.contains(i)) {
            ans.add(i);
        }
    }

    int[] ret = new int[ans.size()];

    int count = 0;
    for(Integer i: ans) {
        ret[count] = i;
        count++;
    }

    return ret;
}

public Set<Integer> getSet(int[] arr) {
    Set<Integer> set = new HashSet<>();

    for(int a: arr) { set.add(a); }
    return set;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM