LeetCode 面试题 16.24. 数对和

文章目录

一、题目

设计一个算法,找出数组中两数之和为指定值的所有整数对。一个数只能属于一个数对。

示例 1:

输入: nums = [5,6,5], target = 11
输出: [[5,6]]

示例 2:

输入: nums = [5,6,5,6], target = 11
输出: [[5,6],[5,6]]

提示:

  • nums.length <= 100000
  • -10^5 <= nums[i], target <= 10^5

点击此处跳转题目

二、C# 题解

使用双指针双向检测,注意要先排序。

csharp 复制代码
public class Solution {
    public IList<IList<int>> PairSums(int[] nums, int target) {
        IList<IList<int>> ans = new List<IList<int>>();
        Array.Sort(nums);
        int i = 0, j = nums.Length - 1; // 双指针
        while (i < j) {
            int sum = nums[i] + nums[j];                                // 两数和
            if (sum == target) ans.Add(new[] { nums[i++], nums[j--] }); // 找到则添加,i、j 均挪位
            else if (sum > target) j--;                                 // 如果大了,右指针左移
            else i++;                                                   // 否则左指针右移
        }
        return ans;
    }
}
  • 时间:216 ms,击败 83.33% 使用 C# 的用户
  • 内存:65.98 MB,击败 16.67% 使用 C# 的用户

直接遍历数组,使用 map 记录出现过的数字和次数,每次查找是否有匹配的 another。

csharp 复制代码
public class Solution {
    public IList<IList<int>> PairSums(int[] nums, int target) {
        IList<IList<int>>    ans = new List<IList<int>>();
        Dictionary<int, int> dic = new Dictionary<int, int>(); // 存储出现过的数字及次数
        foreach (int num in nums) {
            int another = target - num; // 匹配的另一个数
            if (dic.TryGetValue(another, out int value)) { // 尝试找之前是否出现过
                if (value > 0) { // 如果出现过,则次数 - 1,添加结果
                    dic[another]--;
                    ans.Add(new[] { num, another });
                }
                else if (!dic.TryAdd(num, 1)) dic[num]++; // 出现过但次数被用完,添加 num 的记录
            }
            else if (!dic.TryAdd(num, 1)) dic[num]++; // 未出现过,添加 num 的记录
        }
        return ans;
    }
}
  • 时间:204 ms,击败 100.00% 使用 C# 的用户
  • 内存:60.31 MB,击败 100.00% 使用 C# 的用户
相关推荐
无尽的罚坐人生2 小时前
hot 100 73. 矩阵置零
线性代数·算法·矩阵
goodluckyaa2 小时前
thread block grid模型
算法
武帝为此2 小时前
【Rabbit加密算法介绍】
算法·安全
m0_716765233 小时前
数据结构三要素、时间复杂度计算详解
开发语言·数据结构·c++·经验分享·笔记·算法·visual studio
米粒13 小时前
力扣算法刷题 Day 36
算法·leetcode·职场和发展
And_Ii3 小时前
3740. 三个相等元素之间的最小距离 I
c++·算法
csuzhucong3 小时前
puzzle(0334)双面数局
数据结构·算法
强盛机器学习~3 小时前
2026年SCI一区新算法-贝塞尔曲线优化算法(BCO)-公式原理详解与性能测评 Matlab代码免费获取
算法·matlab·进化计算·智能优化算法·元启发式算法·群体智能算法
翟天保Steven3 小时前
空间载波移相干涉算法(SPSI)
算法·激光干涉·精密量测
xin_nai3 小时前
判断质数(Java版)
算法