[TwoPointers][2]Lintcode587. Two Sum - Unique pairs

Amazon | OA 2019 | Two Sum - Unique Pairs

Given an int array nums and an int target, find how many unique pairs in the array such that their sum is equal to target. Return the number of pairs.

Example 1:
Input: nums = [1, 1, 2, 45, 46, 46], target = 47
Output: 2
Explanation:
1 + 46 = 47
2 + 45 = 47
Example 2:
Input: nums = [1, 1], target = 2
Output: 1
Explanation:
1 + 1 = 2
Example 3:
Input: nums = [1, 5, 1, 5], target = 6
Output: 1
Explanation:
[1, 5] and [5, 1] are considered the same.

Related problems:

  • https://leetcode.com/problems/two-sum
  • https://leetcode.com/problems/two-sum-ii-input-array-is-sorted
Solution1: TwoPointers

1.注意重复元素的去重
注意去重的方法;
如果用nums[start] == nums[start+1] start ++, 如果nums[start+1]还是一个重复的元素,nums[start+2]不是重复的元素,那么这种方法就不能去掉nums[start+1]。

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 < 2) return 0;
        
        Arrays.sort(nums);
        
        int start = 0, end = nums.length -1;
        int sum = 0;
        
        while(start < end) {

            if(nums[start] + nums[end] == target){
                ++ sum;
                ++ start;
                -- end;
                while(start < end && nums[start] == nums[start - 1] ){
                    ++ start;
                }
                
                while(start < end && nums[end] == nums[end + 1] ){
                -- end;
                }
            }
            else if(nums[start] + nums[end] > target){
                -- end;
                
            }else {
                ++ start;
            }
            
        }
        
        return sum;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值