Middle+
Java Tasks 1. Write an implementation of the method: /** * @param a – array of numbers, the length of the array can be more than 10 million. * @return array of numbers with no duplicates. The order of numbers in the original array must be preserved. For duplicates, the last element should be kept, for example, for {2,1,4,2,3} the correct solution is {1,4,2,3}, not {2,1,4,3} If there is an element less than 0 in the input array, an error should be thrown. For example, for {2,3,-1,5} the processing should end with an error. */ public static double[] task(double[] a) { }
sobes.tech AI
Answer from AI
To solve the task:
- Check that there are no negative numbers in the array, otherwise throw an exception.
- Determine the last occurrence of each number in the array.
- Iterate through the array and keep only those elements whose index matches their last occurrence.
Since the array can be very large (more than 10 million elements), it is important to use efficient data structures and algorithms with linear complexity.
Example implementation in Java:
import java.util.*;
public static double[] task(double[] a) {
// Check for negative elements
for (double num : a) {
if (num < 0) {
throw new IllegalArgumentException("Array contains a negative number: " + num);
}
}
// Map each number to its last index
Map<Double, Integer> lastIndexMap = new HashMap<>();
for (int i = 0; i < a.length; i++) {
lastIndexMap.put(a[i], i);
}
// Collect results, keeping only elements whose index matches their last occurrence
List<Double> resultList = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
if (lastIndexMap.get(a[i]) == i) {
resultList.add(a[i]);
}
}
// Convert list back to array
double[] result = new double[resultList.size()];
for (int i = 0; i < result.length; i++) {
result[i] = resultList.get(i);
}
return result;
}
This approach preserves the order of elements and keeps only the last occurrences of duplicates.