Given [1, 2, 3, 4, 5] and target 8, print the two indices (0-based) separated by space.
| Test | Status | Details |
|---|
Ready — edit the code above and click Run or Submit.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
int[] nums = { 1, 2, 3, 4, 5 };
int target = 8;
var map = new Dictionary<int, int>();
for (int j = 0; j < nums.Length; j++) {
int need = target - nums[j];
if (map.ContainsKey(need)) { Console.WriteLine(map[need] + " " + j); return; }
map[nums[j]] = j;
}
}
}
Try solving on your own first, then reveal the official answer.
Classic hash-map two sum — O(n) time.