703367. Distinct absolute array elements
Easy
Distinct Absolute Array Elements
Summary
Given an array of integers, find and return all distinct absolute elements. The problem is related to arrays and sorting concepts.
Detailed Explanation
In this problem, we are given an array arr containing integer values. We need to find the distinct absolute values from the given array. For example, if the input array is [1, -2, 3, -4], our function should return [1, 2, 3, 4].
Here's a step-by-step breakdown of the solution:
- First, we initialize an empty set
distinctAbsto store distinct absolute values. - Then, we iterate over each element in the input array
arr. - For each element, we calculate its absolute value using the built-in
Math.abs()function in Java and Python, or by directly taking the absolute of the integer value for C++ and JavaScript. - We then add this calculated absolute value to our set
distinctAbs. Since sets in most programming languages do not allow duplicate values, this ensures that we only store unique absolute values. - Finally, we convert our set
distinctAbsback into a list or array (depending on the language) and return it as the result.
Time complexity for this solution is O(n), where n is the number of elements in the input array. This is because we are iterating over each element once. Space complexity is also O(n) due to the set distinctAbs that stores unique absolute values.
Optimized Solutions
Java
import java.util.*;
public class Main {
public static int[] distinctAbsolute(int[] arr) {
Set<Integer> distinctAbs = new HashSet<>();
for (int num : arr) {
distinctAbs.add(Math.abs(num));
}
return distinctAbs.stream().mapToInt(Integer::intValue).toArray();
}
}