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

前端 未结 14 1956
萌比男神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 11:57

        public void sumOfTwoQualToTargetSum()
        {
            List list= new List();
            list.Add(1);
            list.Add(3);
            list.Add(5);
            list.Add(7);
            list.Add(9);
    
            int targetsum = 12;
    
            int[] arr = list.ToArray();
    
            for (int i = 0; i < arr.Length; i++)
            {
                for (int j = 0; j < arr.Length; j++)
                {
                    if ((i != j) && ((arr[i] + arr[j]) == targetsum))
                    {
                        Console.Write("i =" + i);
                        Console.WriteLine("j =" + j);
                    }
                }
            }
        }
    

提交回复
热议问题