Problem
You are given an integer array nums
. This array contains n
elements, where exactly n - 2
elements are special****numbers. One of the remaining
two elements is the sum of these special numbers , and the other is an outlier.
An outlier is defined as a number that is neither one of the original special numbers nor the element representing the sum of those numbers.
Note that special numbers, the sum element, and the outlier must have distinct indices, but may share the same value.
Return the largest**** potentialoutlier in nums
.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
3 <= nums.length <= 10^5
-1000 <= nums[i] <= 1000
- The input is generated such that at least one potential outlier exists in
nums
.
Solution
Method 1 – Hash Set and Total Sum
Intuition
The sum of all special numbers is present in the array, and the outlier is the remaining number. For each number, try removing it and see if the rest can be split into (n-2) numbers and their sum.
Approach
- Compute the total sum of the array.
- For each number x in nums, let s = total - x. If s - y (for some y ≠ x) is also in nums, then x or y could be the outlier. Try all possibilities and track the largest valid outlier.
- Use a Counter to handle duplicates.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
(can be optimized to O(n) with sorting and set, but this is the direct approach). - 🧺 Space complexity:
O(n)