C# Run this code will fail to pass tests due to "time limit exceeded test"


  • 0
    S
    public int[] TwoSum(int[] nums, int target)
        {
            var numberDic = new Dictionary<int,int>();
    
            for (int i = 0; i < nums.Length; i++)
            {
                numberDic.Add(i, nums[i]);
            }
    
            for (int i = 0; i < nums.Length; i++)
            {
                int leftOver = target - nums[i];
                if (numberDic.ContainsValue(leftOver) && (numberDic.First(x => x.Value.Equals(leftOver)).Key != i))
                {
                    return new[] {i, numberDic.First(x=>x.Value.Equals(leftOver)).Key};
                }
            }
            throw new Exception("NO!!!");
        }
    

    The bare maximum could be the second loop is failing to use O(n) finding out the key of the dictionary, anyone knows how to implement that through C#?


Log in to reply
 

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