74.7k views
4 votes
Add a method named "problem9" that accepts two arrays of integer values. Find the elements that only appear in one of the arrays. You may assume each array contains unique elements. Return the result. Test case: Array1 is {1, 4, 3, 2, 5}, Array2 is {7, 5, 4, 6}. Return {1, 3, 2, 7, 6}.

a) Implement the "problem9" method as described.
b) The method should return the common elements between the two arrays.
c) The method should return the union of elements from both arrays.
d) The method should return an empty array.

1 Answer

4 votes

Final answer:

To find the elements that only appear in one of the arrays, iterate through each element in one array and check if it exists in the other array. If not, add it to a new array. Finally, return the new array as the result.

Step-by-step explanation:

To solve this problem, you can iterate through each element in one array and check if it exists in the other array. If an element is not found, add it to a new array that will store the elements that only appear in one of the arrays. Finally, return the new array as the result.

  1. Create an empty ArrayList to store the elements that only appear in one of the arrays.
  2. Iterate through each element in the first array.
  3. Check if the element exists in the second array using the contains() method.
  4. If the element does not exist in the second array, add it to the new ArrayList.
  5. Repeat steps 2-4 for the second array.
  6. Convert the ArrayList to an array using the toArray() method and return it as the result.

Here's the code implementation for the 'problem9' method:

import java.util.ArrayList;

public class MyClass {

public static int[] problem9(int[] array1, int[] array2) {
ArrayList<Integer> result = new ArrayList<>();

for (int num : array1) {
if (!contains(array2, num)) {
result.add(num);
}
}

for (int num : array2) {
if (!contains(array1, num)) {
result.add(num);
}
}

return result.toArray(new int[result.size()]);
}

private static boolean contains(int[] array, int target) {
for (int num : array) {
if (num == target) {
return true;
}
}
return false;
}

}
User Jimmy P
by
8.0k points