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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace twosum
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
int[] test = new int[] { 2, 5, 7, 11 };
int targetNum = 9;
int[] result = p.GetIndex(test, targetNum);
Console.WriteLine(result[0]+" "+result[1]);
}
public int[] GetIndex(int[] array, int target)
{
Dictionary<int,int> symbol = new Dictionary<int,int>();
int[] res = new int[2];
for(int i=0;i<array.Length;i++)
{
symbol.Add(array[i], i);
}
for(int j=0;j<array.Length;j++)
{
int t = target - array[j];
//int f;
if(symbol.ContainsKey(t) && symbol[t]!=j)
{
res[0] = j;
res[1] = symbol[t];
break;
}
}
return res;
}
}
}