Sponsored
Sponsored
This approach utilizes a HashSet to keep track of the numbers we have encountered. As we iterate through the list, we check both the presence of a number and its negative in the HashSet. We update the largest number that satisfies the condition.
Time Complexity: O(n), since we iterate through the array once.
Space Complexity: O(1), since the hash set array size is always constant and independent of input size.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int LargestEqualPositiveNegative(int[] nums) {
6 HashSet<int> numSet = new HashSet<int>();
7 int largest = -1;
8
9 foreach (int num in nums) {
10 if (numSet.Contains(-num)) {
11 largest = Math.Max(largest, Math.Abs(num));
12 }
13 numSet.Add(num);
14 }
15 return largest;
16 }
17
18 public static void Main() {
19 Solution solution = new Solution();
20 int[] nums = {-1, 2, -3, 3};
21 Console.WriteLine(solution.LargestEqualPositiveNegative(nums)); // Output: 3
22 }
23}
The solution maintains a HashSet for quick presence checking of integers. The loop checks if each number's negative counterpart exists, updating the maximum if necessary.
In this approach, we first sort the array so that we can efficiently find pairs of positive and negative numbers. Once sorted, we use two pointers: one starting from the beginning (for negative numbers) and one from the end (for positive numbers) to find the largest integer pair where both a positive and its negative exist.
Time Complexity: O(n log n) for the sorting operation.
Space Complexity: O(1) additional space beyond input storing.
By sorting, the array leverages two pointers to find matching number pairs with opposite signs effectively. We examine pairs equating to zero to decide the largest possible valid integer.