1、Two Sum

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].


代码:
static void Main(string[] args)
{
    int[] nums = { 2, 7, 11, 15 };
    var res=Twosum(nums, 9);
    Console.WriteLine($"[{res[0]},{res[1]}]");
    Console.ReadKey();
}

public int[] TwoSum(int[] nums, int target) 
{
    var dictionary=new Dictionary<int,int>();
    for (int i = 0; i < nums.Length; i++)
    {
        var nn = target - nums[i];
        if (dictionary.ContainsKey(nn))
        {
            return new int[]{ dictionary[nn],i};
        }
        dictionary[nums[i]] = i;
    }
    throw new ArgumentException();
}
解析:

输入:整型数组num和整型目标值。
输出:一个数组,由得到目标值的两个数的索引构成。
代码思想
  首先,字典的key是num数组中的元素,value是这个元素所对应的索引。
  其次,通过遍历整个数组,即假设已知第一个数,求出第二个数并判断是否在字典中,若在,则返回第二个数在字典中的value值与第一个数的索引组成的数组。若不在,将第一个元素和索引添加到字典中,继续判断第二个数。
  最后,若找到会返回数组,若没有则抛出异常。
时间复杂度:O(n)






内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!