Two Sum - Unique pairs

Description:

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.

Ex:

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

1 + 46 = 47
2 + 45 = 47

解法一:

思路:

双指针 + 哈希表

Code:

public class Solution {
    /**
     * @param nums an array of integer
     * @param target an integer
     * @return an integer
     */
    public int twoSum6(int[] nums, int target) {
        // Write your code here
        if (nums == null || nums.length == 0){
            return 0;
        }

        Set<Integer> set = new HashSet<>();

        Arrays.sort(nums);

        int left = 0;
        int right = nums.length - 1;
        int count = 0;

        while (left < right){
            if (nums[left] + nums[right] == target){
                count++;
                set.add(nums[left]);
                left++;
                while ((left < right) && (set.contains(nums[left]))){
                    left++;
                }

            } else if (nums[left] + nums[right] < target){
                left++;
            } else {
                right--;
            }
        }
        return count;
    }

}

解法二:

思路:

单纯双指针:

Code:

public class Solution {
    /**
     * @param nums an array of integer
     * @param target an integer
     * @return an integer
     */
    public int twoSum6(int[] nums, int target) {
        // Write your code here
        if (nums == null || nums.length == 0){
            return 0;
        }


        Arrays.sort(nums);

        int left = 0;
        int right = nums.length - 1;
        int count = 0;

        while (left < right){
            if (nums[left] + nums[right] == target){
                count++;
                right--;
                left++;
                while ((left < right) && (nums[left - 1] == nums[left])){
                    left++;
                }
                // while ((left < right) && (nums[right + 1] == nums[right])){
                //     right--;
                // }

            } else if (nums[left] + nums[right] < target){
                left++;
            } else {
                right--;
            }
        }
        return count;
    }

}

小贴士:

用双指针处理的Two Sum问题要先排序,同时要注意防止数组越界

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值