C# O(n) solution using Dictionary (beats %97.82)


  • 0
    K
    public class Solution {
        public int[] TwoSum(int[] nums, int target) {
            int len = nums.Length;
            int[] a = new int[2];
            Dictionary<int,int> hash = new Dictionary<int,int>();
            for (int i=0;i<len;i++) {
                int complement = target - nums[i];
                if (hash.ContainsKey(complement)) {
                    a[0]=i;
                    a[1]=hash[complement];
                    return a;
                }
                else {
                    if (!hash.ContainsKey(nums[i]))
                        hash.Add(nums[i],i);
                }
            }
            return a;
        }
    }
    

Log in to reply
 

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