饭后小甜点leetcode——k数之和系列

两数之和

两数之和

leetcode题目链接

【知识点】:HashTable
【思路】:从左向右扫描nums数组,每访问一个数,就看一下target减去这个数在不在map中,如果在的话说明这个数之前有一个数等于target减当前这个数,也就是说,这两数加起来等于target。
【代码】:

public int[] TwoSum(int[] nums, int target)
{
   
    var map = new Dictionary<int, int>();
    for (var i = 0; i < nums.Length; i++)
    {
   
        if (map.ContainsKey(target - nums[i]))
        {
   
            return new int[] {
    map[target - nums[i]], i };
        }
        if (!map.ContainsKey(nums[i]))
        {
   
            map.Add(nums[i], i);
        }
    }
    return null;
}

两数之和 II - 输入有序数组

leetcode题目链接

【知识点】:双指针
【思路】:因为是排好序的数组,所以从数组两端向中间走,如果当前l和r指针指向的数的和大于target,r–,小于的话,l++,等于就返回。

public int[] TwoSumII(int[] numbers, int target)
{
   
    int l = 0; int r = numbers.Length - 1;
    while (l < r)
    {
   
        if (numbers[l] + numbers[r] == target)
        {
   
            return new int[] {
    l + 1, r + 1 };
        }
        if (numbers[l] + numbers[r] > target)
        {
   
            r--;
        }
        else
        {
   
            l++;
        }
    }
    return null;
}

两数之和 III - 数据结构设计

leetcode题目链接
【思路】:就是把基础版两数之和包成数据结构。

public class TwoSum
{
   
    List<int> nums = new List<int>();
    /** Initialize your data structure here. */
    public TwoSum() {
    }

    /** Add the number to an internal data structure.. */
    public void Add(int number)
    {
   
        nums.Add(number);
    }

    /** Find if there exists any pair of numbers which sum is equal to the value. */
    public bool Find(int target)
    {
   
        var map = new Dictionary<int, int>();
        for (var i = 0; i < nums.Count; i++)
        {
   
            if (map.ContainsKey(target - nums[i]))
            {
   
                return true;
            }
            if (!map.ContainsKey(nums[i]))
            {
   
                map.Add(nums[i], i);
            }
        }
        return false;
    }
}

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值