C# solution using a dicitionary


  • 0
    D
    public class Solution {
        public int[] TwoSum(int[] nums, int target) {
            Dictionary<int,int> book = new Dictionary<int,int>();
            for(int i = 0; i < nums.Length; i++){
                if (book.ContainsKey(target - nums[i])){
                    return new int[2]{book[target - nums[i]] + 1, i + 1};
                }
                if (book.ContainsKey(nums[i])){
                    book[nums[i]] = i;
                }
                else{
                    book.Add(nums[i], i);
                }
            }
            return null;
        }
    }

  • 0
    G

    you can decrease your execution time by using

    int value;
    book.TryGetValue('key', out value);
    

    This reduces your dictionary access by half. You're checking if the key exists, and then you're accessing it again at the same point for it's return value. Refactor it using TryGetValue and you'll see a slight increase.


Log in to reply
 

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