Accepted C# O(n) Solution


  • 1
    S

    public class Solution
    {
    public int[] TwoSum(int[] nums, int target)
    {
    int[] result = new int[2];
    Dictionary<int, int> map = new Dictionary<int, int>();
    // map(value, index), value= nums[i], index=i
    int con;
    for (int i = 0; i < nums.Length; i++)
    {
    con = target - nums[i];// get the difference between target and nums[i]
    if (map.ContainsKey(con))// check if difference exist in dictionary
    {
    result[0] = map[con]; // first index
    result[1] = i; // second index
    return result;
    }
    else if(!map.ContainsKey(nums[i]))// add the new pair if the value is not already added.
    {
    map.Add(nums[i], i);
    }

            }
            return result;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.