美文网首页
Sep-26-2018

Sep-26-2018

作者: 雨生_ | 来源:发表于2018-09-26 22:05 被阅读3次

争取每周做五个LeedCode题,定期更新,难度由简到难

Title: Two Sum

Description:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Difficulty:

Easy

Implement Programming Language:

C#

Answer:

下面的代码有个小问题,不能解决重复的数据,比如说数组里有两个10,就会报错,因为字典的Key不能重复,没有太好的解决办法,题目也没有提及这块,就暂时认为输入的数据都是没有重复的。
这个解决方法时间复杂度是O(n),空间复杂度也是O(n)

public int[] twoSum(int[] args,int target)
        {
            var dic = new Dictionary<int, int>();
            for (int i = 0; i < args.Length; i++)
            {
                var subValue = target - args[i];
                if (dic.ContainsKey(subValue))
                    return new int[] { dic[subValue],i };
                dic.Add(args[i], i);
            }
            return null;
        }
Github

相关文章

  • Sep-26-2018

    争取每周做五个LeedCode题,定期更新,难度由简到难 Title: Two Sum Description: ...

网友评论

      本文标题:Sep-26-2018

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