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

前端 未结 14 1952
萌比男神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;
    }
    
    0 讨论(0)
  • 2021-01-30 12:20

    This is in Java : This even removes the possible duplicates.. Runtime - O(n^2)

    private static int[] intArray = {15,5,10,20,25,30};
    private static int sum = 35;
    
    private static void algorithm()
    {
        Map<Integer, Integer> intMap = new Hashtable<Integer, Integer>();
        for (int i=0; i<intArray.length; i++) 
        {
            intMap.put(i, intArray[i]);
            if(intMap.containsValue(sum - intArray[i]))
                System.out.println("Found numbers : "+intArray[i] +" and "+(sum - intArray[i]));
    
        }
        System.out.println(intMap);
    }
    
    0 讨论(0)
提交回复
热议问题