587. Two Sum - Unique pairs Given an array of integers, find how many unique pairs in the array such that their sum is equal to a specific target number. Please return the number of pairs.

Example

Given nums = [1,1,2,45,46,46], target = 47
return 2

1 + 46 = 47
2 + 45 = 47

Python Solutions

class Solution:
    """
    @param: nums: an array of integer
    @param: target: An integer
    @return: An integer
    """
    def twoSum6(self, nums, target):
        # write your code here
        count = 0
        nums.sort()
        n = len(nums)
        i, j = 0, n - 1
        while i < j:
            if i != 0 and nums[i] == nums[i - 1]:
                i += 1
                continue
            
            if j != n - 1 and nums[j] == nums[j + 1]:
                j -= 1
                continue
            
            if nums[i] + nums[j] == target:
                count += 1
                i += 1
                j -= 1
            elif nums[i] + nums[j] < target:
                i += 1
            else:
                j -= 1
                
        return count
    
    # Total Runtime: 908 ms
    # 100% test cases passed.