【两次过】【双指针】Lintcode 587. 两数之和 - 不同组成

本文介绍了一种算法,用于在一整数数组中找到所有不同的元素对,这些元素对的和等于给定的目标值。通过使用双指针法并跳过重复元素,该算法能够有效地解决问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给一整数数组, 找到数组中有多少组 不同的元素对 有相同的和, 且和为给出的 target 值, 返回对数.

样例

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

解题思路:

双指针法。不同的是这次需要找不同的元素对,所以需要对相同的元素跳过。

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 l = 0;
        int r = nums.length-1;
        int res = 0;
        
        while(l < r){
            //用来过滤掉相同的元素
            if(l > 0 && nums[l] == nums[l-1]){
                l++;
                continue;
            }
            if(r < nums.length-1 && nums[r] == nums[r+1]){
                r--;
                continue;
            }
            
            if(nums[l] + nums[r] == target){
                l++;
                r--;
                res++;
            }else if(nums[l] + nums[r] < target)
                l++;
            else
                r--;
        }
        
        return res;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值