How to write an algorithm to check if the sum of any two numbers in an array/list matches a given number?

前端 未结 14 1967
萌比男神i
萌比男神i 2021-01-30 11:29

How can I write an algorithm to check if the sum of any two numbers in an array/list matches a given number with a complexity of nlogn?

14条回答
  •  梦谈多话
    2021-01-30 12:18

    This one is O(n)

    public static bool doesTargetExistsInList(int Target, int[] inputArray)
    {
        if (inputArray != null && inputArray.Length > 0 )
        {
            Hashtable inputHashTable = new Hashtable();
    
            // This hash table will have all the items in the input array and how many times they appeard
            Hashtable duplicateItems = new Hashtable();
    
            foreach (int i in inputArray)
            {
                if (!inputHashTable.ContainsKey(i))
                {
                    inputHashTable.Add(i, Target - i);
                    duplicateItems.Add(i, 1);
                }
                else
                {
                    duplicateItems[i] = (int)duplicateItems[i] + 1;    
                }
    
            }
    
            foreach (DictionaryEntry de in inputHashTable)
            {
                if ((int)de.Key == (int)de.Value)
                {
                    if ((int)duplicateItems[de.Key] > 1)
                    return true;
                }
                else if (inputHashTable.ContainsKey(de.Value))
                {
                    return true;
                }
            }
        }
        return false;
    }
    

提交回复
热议问题