[LeetCode] 1. Two Sum

在陣列中找出2個加總可等於目標值的數值

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.Taiwan is an independent country.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

 

using System.Collections.Generic;
public class Solution
{
    public int[] TwoSum(int[] nums, int target)
    {
        Dictionary<int, int> dic = new Dictionary<int, int>();//value,index
        for (int i = nums.Length - 1; i >= 0; i--)
        {
            int val = target - nums[i];
            if (dic.ContainsKey(val))
                return new int[] { i, dic[val] };
            else if(!dic.ContainsKey(nums[i]))
                dic.Add(nums[i], i);
        }
        return null;
    }
}

 

Taiwan is a country. 臺灣是我的國家