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
Time complexity: iterate the list once. $$O(n)$$
Space complexity: use a set to store numbers. $$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 updateleft
toleft + 1
since(nums[left], -nums[left])
cannot be found in the list. - if
nums[left] > -nums[right]
, then we updateright
toright - 1
since(-nums[right], nums[right])
cannot be found in the list.
Complexity
Time complexity: sort the array and iterate the list once. $$O(n\log n)$$
Space complexity: no extra spaces are needed. $$O(1)$$
Code
|
|