美文网首页
Leecode[1] 两数之和

Leecode[1] 两数之和

作者: 饭板板 | 来源:发表于2020-09-15 16:02 被阅读0次

题目

给定一个整数数组 nums和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

【题目解析】

  • 当两数之和不存在于数组中,返回 null。(面试时需要陈述对于这种临界情况的处理)。
  • 数组中是否可以存在重复元素,以及面试者对于重复元素如何处理。

解法1

    public int[] TwoSumV2(int[] nums, int target) {
        for (int i = 0; i < nums.Length; i++)
        {
            for (int j = i+1; j < nums.Length; j++)
            {
                if(nums[i]+nums[j]==target)
                {
                    return new int[]{i,j};
                }
            }
        }

        return null;
    }

注意点:

  • 内置循环从 i+1 开始。
  • 不用判断同一个元素不能使用两遍。

小结:

  • 时间复杂度 O(n^2)。
  • 空间复杂度 O(1)。

解法2

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

        for (int i = 0; i < nums.Length; i++)
        {
            var ei=target - nums[i];
            if (temp.ContainsKey(ei) && temp[ei] != i) 
            {
                return new []{temp[ei],i};
            }
        }

        return null;
    }

注意点:

  • 不要忘记判断同一个元素不能使用两遍。
  • 对于数组中含有重复元素的处理。

小结:

  • 时间复杂度 O(n)。
  • 空间复杂度 O(n)。

解法3

    public int[] TwoSum(int[] nums, int target) {
        var temp =new Dictionary<int,int>();

        for (int i = 0; i < nums.Length; i++)
        {
            var expected=target-nums[i];
            if (temp.ContainsKey(expected))
            {
                return new int[]{temp[expected], i};
            }

            if (!temp.ContainsKey(nums[i]))
            {
                temp.Add(nums[i],i);
            }
        }
    }

注意点:

  • 对于数组中含有重复元素的处理。
  if (!temp.ContainsKey(nums[i]))
  {
      temp.Add(nums[i],i);
  }

小结:

  • 时间复杂度 O(n)。
  • 空间复杂度 O(n)。

相关文章

  • leecode 1 两数之和

    求数组内满足特定值的元素索引 方法一 这种方法容易想,时间复杂度为n2 方法二 这种方法不是很容易想,但很有趣 5...

  • Leecode[1] 两数之和

    题目 给定一个整数数组 nums和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的...

  • leecode刷题(8)-- 两数之和

    leecode刷题(8)-- 两数之和 两数之和 描述: 给定一个整数数组 nums 和一个目标值 target,...

  • leecode:01 两数之和

    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的...

  • LC吐血整理-Array篇

    github-Leecode_summary 1. 两数之和 hash() 用于获取取一个对象(字符串或者数值等)...

  • LeeCode01-两数之和

    题目来源: https://leetcode-cn.com/problems/two-sum/[https://l...

  • 2018-07-12

    C++ map hashmap java hashmap 对比分析 首先 这个是在做leecode上的两数之和时遇...

  • 1.两数之和-twoSum

    链接 LeeCode-1-两数之和 参考 知乎 Git 题目描述 给定一个整数数组 nums 和一个目标值 tar...

  • Leecode[15] 三数之和

    题目 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b...

  • 1、两数之和

    https://leetcode-cn.com/problems/two-sum/[https://leetcod...

网友评论

      本文标题:Leecode[1] 两数之和

      本文链接:https://www.haomeiwen.com/subject/mwdfyktx.html