Given a list containing integers, find the largest positive integer that its negative also exists in the list.
Intuition
There are two ways to solve the problem.
- One way is to use two sum, we find the all pairs of integers such that their sum is zero and the one is the negative of the other.
- The second way is to use two pointer, we move left and right pointer utils their absolute values are equal.
Approach 1: two sum
Similar to Two Sum, for each num in nums, we store its negative -num in the hash table,
however, notice that the added term can be determined by num, we can use a set instead.
Complexity
- $$O(n)$$
- $$O(n)$$
Code
| |
Approach 2: two pointer
We first sort the lists, then we use left=0 and right=length(nums) pointer to iterate the list, there are three cases:
- if
nums[left] == -nums[right], then we directly returnnums[right]since this is the largest one (note that the list is sorted) - if
nums[left] < -nums[right], then we updatelefttoleft + 1since(nums[left], -nums[left])cannot be found in the list. - if
nums[left] > -nums[right], then we updaterighttoright - 1since(-nums[right], nums[right])cannot be found in the list.
Complexity
- $$O(n\log n)$$
- $$O(1)$$
Code
| |