美文网首页
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] 两数之和

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