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# 的用户
相关推荐
JieE2123 分钟前
手把手带你用虚拟头节点实现单链表,搞定所有边界问题
javascript·算法
魔法阵维护师4 分钟前
从零开发游戏需要学习的c#模块,第二十一章(精灵动画 —— 让角色走起来)
学习·游戏·c#
Eiceblue4 分钟前
使用 C# 高效替换 PDF 中的文本:全页、区域与正则匹配
visualstudio·pdf·c#
搞科研的小刘选手27 分钟前
【大连市计算机学会主办】第三届图像处理、智能控制与计算机工程国际学术会议(IPICE 2026)
图像处理·人工智能·深度学习·算法·计算机·数据挖掘·智能控制
人月神话-Lee29 分钟前
【图像处理】高斯模糊——最优雅的模糊算法
图像处理·人工智能·算法·ios·ai编程·swift
大熊背41 分钟前
双目拼接竖缝消除(ISP 分区锐化实操方案) 优化方案
人工智能·算法·双目拼接
_日拱一卒44 分钟前
LeetCode:105从前序与中序遍历序列构造二叉树
算法·leetcode·职场和发展
MicroTech20251 小时前
微算法科技(NASDAQ :MLGO)发布基于NEQR技术的新型量子视频处理算法,重构智能视觉底层逻辑
科技·算法·音视频
techdashen1 小时前
Async Rust 近况补课:从 `async-trait` 到原生 async trait
网络·算法·rust
一行代码一行诗++1 小时前
循环的嵌套
数据结构·算法