如何在一个数组里面找到两个数,使它们之和为参数所指定的数?比如{1,2,3,4,5},指定6,得到1,5 和 2,4

解决方案 »

  1.   


    int num = 6;
            int num1 = 0;
            int num2 = 0;
            string str = "";
            int[] arr = { 1, 2, 3, 4, 5 };
            int len = arr.Length;
            for (int i = 0; i < len; i++)
            {
                num1 = arr[i];
                for (int j =(i+1); j < len;j++ )
                {
                    num2 = arr[j];
                    if ((num1 + num2) == num)
                    {
                        str += num1.ToString() + "," + num2.ToString() + " ";
                    }
                }
            }
            Response.Write("结果为:"+str);
      

  2.   


            public static void Test()
            {
                Int32[] paras = { 1, 2, 3, 4, 5 };
                List<Int32> temp = new List<Int32>(paras);
                temp.Sort();
                Int32 i = 6;
                var v = from p1 in temp from p2 in temp where p1 + p2 == i select new { p1, p2 };
                foreach (var p in v)
                {                
                    Int32 p1 = p.p1;
                    Int32 p2 = p.p2;
                    if (p1 <= p2)
                    {
                        if (p1 != p2 || (p1 == p2 && (temp.FindAll((pa) => { if (pa == p1) return true; else return false; }).Count<Int32>() > 1)))
                        {
                            Console.WriteLine(p1 + "   " + p2);
                        }
                    }
                }
            }
      

  3.   


     int[] a={1,2,3,4,5,6};
            int Number = 6;
            ArrayList NumberList = new ArrayList();
            for(int i=0;i<a.Length;i++)
            {
                for (int j = i + 1; j < a.Length;j++ )
                {
                    if (a[i] + a[j] == Number)
                    {
                        NumberList.Add(a[i].ToString() + "," + a[j].ToString());
                    }
                }
            }