Skip to content
本页目录

0001-两数之和

https://leetcode.cn/problems/two-sum/

给定一个整数数组 nums和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那两个整数,并返回它们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。 你可以按任意顺序返回答案。

示例 1:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

示例 2:

输入:nums = [3,2,4], target = 6
输出:[1,2]

示例 3:

输入:nums = [3,3], target = 6
输出:[0,1]

提示:

2 <= nums.length <= 10^4
-10^9 <= nums[i] <= 10^9
-10^9 <= target <= 10^9
只会存在一个有效答案

进阶:你可以想出一个时间复杂度小于 O(n^2) 的算法吗?

思路分析

暴力方法是循环两层,依次计算 nums[i] + nums[j] 是否等于 target,时间复杂度 O(n^2) 优化方法:使用字典(哈希表),保存不满足条件的数字的下标,所以当循环到下一个数的时候,计算 key = target - nums[i] 如果 key 存在字典中,则说明找到了满足条件的数据,从 字典中取得下标和当前下标返回

实现代码

csharp
public class Solution {
    public int[] TwoSum(int[] nums, int target) {
        Dictionary<int,int> dict = new Dictionary<int,int>();
        for(int i=0; i<nums.Length; i++){
            int key = target - nums[i];
            if(dict.ContainsKey(key)){
                return new int[]{dict[key],i};
            }
            else{
                //放置重复数据加入字典
                if(!dict.ContainsKey(nums[i])){
                    dict.Add(nums[i],i);
                }
            }
        }
        return new int[]{};
    }
}

Released under the MIT License.