C# code error "Time Limit Exceeded" even though not O(n^2) solution


  • 0
    J

    public Tuple<int, int> FindTwoSumIndices(int[] array, int targetValue)
    {
    if (array.Length == 0 || array.Length == 1)
    {
    throw new ArgumentNullException("array");
    }

            if (array.Length == 2)
            {
                if (array[0] + array[1] == targetValue)
                {
                    return Tuple.Create(0, 1);
                }
                else
                {
                    return Tuple.Create(-1, -1);
                }
            }
    
            IList<HashMap> indexMap = new List<HashMap>();           
    
            for (int k = 0; k < array.Length; k++ )
            {
                indexMap.Add(new HashMap() { Key = array[k], Value = k });
            }
    
            for (int i = 0; i < array.Length; i++ )
            {
                if (indexMap.Any(h => h.Key.Equals(targetValue - array[i])))
                {
                    int index1 = i;
                    int index2 = indexMap.Where(k => k.Key.Equals(targetValue - array[i])).First().Value;
    
                    return Tuple.Create(index1 + 1, index2 + 1);
                }
            }
            
            return Tuple.Create(-1, -1);
    

    }

    private class HashMap
    {
    public int Key { get; set; }
    public int Value { get; set; }
    }


Log in to reply
 

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