A simple thought on the algorithm of "finding all pairs of all and fixed numbers in an array"

Source: Internet
Author: User

A description of the topic

There is an array a[1000] with 1000 integers in it, find all the pairs of numbers and m in the array. For example, the array is-1,2,4,6,5,3,4,2,9,0,8,3, then and the number of 8 pairs has ( -1,9), (2,6), (4,4), (5,3), (5,3), (0,8).

Second, the most common algorithm

In the case of irreducible complexity, the simplest algorithm for this problem is as follows:

private static List<int[]> UseNormalWay(int[] arr, int sumTotal)
         {
             List<int[]> result = new List<int[]>();
             for (int i = 0; i < arr.Length; i++)
             {
                 int expectNum = sumTotal - arr[i];
                 for (int j = i + 1; j < arr.Length; j++)
                 {
                     if (arr[j] == expectNum)
                     {
                         result.Add(new int[]{arr[i],  expectNum});
                     }
                 }
             }
             return result;
         }

Use a two-tier loop to find all the pairs of numbers that are sumtotal for a fixed number, and the number pairs to be found in the list. But the complexity of the algorithm is a bit high, actually doing some repetitive work while traversing:

1 There is no need to deal with the previously paired sequence in the subsequent cycle.

2 when looking for numbers that are sumtotal with a certain number, there should be some processes that can be used with each other.

Based on these two points, it is possible to refer to the idea of 01 backpacks or dynamic programming (perhaps improperly cited, and I have a superficial understanding of both ideas and understandings) to improve the algorithm and use the recursive operation.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.