LintCode 58: Two Sum - Unique pairs (双指针典型题)

  1. 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

解法1:
典型双指针题,用到了map。
Note:

  1. mp[nums[p1]] = nums[p2]
    不能写成mp[p1] = p2
class Solution {
public:
    /**
     * @param nums: an array of integer
     * @param target: An integer
     * @return: An integer
     */
    int twoSum6(vector &nums, int target) {
        int result = 0;
        map mp;
        
        int len = nums.size();
        if (len == 0) return 0;
        
        sort(nums.begin(), nums.end());
        
        int p1 = 0, p2 = len - 1;
        
        while (p1 < p2) {
            int sum = nums[p1] + nums[p2];
            
            if (sum == target) {
                mp[nums[p1]] = nums[p2];
                p1++;
                p2--;
            }else if (sum < target) {
                p1++;   
            } else {
                p2--;
            }
        }
        
        return mp.size();
    }
};

解法2:用pair
注意:这里不能用unordered_set> hashmap。因为pair 没有指定pair之间如何比大小,所以insert的时候编译器不知道如何处理。除非重载operator <。

class Solution {
public:
    /**
     * @param nums: an array of integer
     * @param target: An integer
     * @return: An integer
     */
    int twoSum6(vector<int> &nums, int target) {
        int n = nums.size();

        set<pair<int, int>> hashmap;
        sort(nums.begin(), nums.end());
        int p1 = 0, p2 = n - 1;
        while(p1 < p2) {
            int sum = nums[p1] + nums[p2];
            if (sum < target) {
                p1++;
            } else if (sum > target) {
                p2--;
            } else {
                hashmap.insert({nums[p1], nums[p2]});
                p1++;
                p2--;
            }
        }
        
        return hashmap.size();
    }
};

代码同步在
https://github.com/luqian2017/Algorithm

你可能感兴趣的:(LintCode 58: Two Sum - Unique pairs (双指针典型题))