2015 prospective energy Campus Recruitment pen questions (Tongji University station)

Source: Internet
Author: User

For a given descending sequence, given an n. Find two numbers in the array so that their sum equals the given number. Requires a time complexity of O (n).

BOOL Findsumelements (int array[], int length, int sum, int *elem1, int *elem2) {if (length = 0) {return
    False
                                                                                                                                    }
    int tempsum = 0;                                                                                                                                                                                   Record elem1 and ELEM2 values in the array in the lower ordinal number//elem1 from the first element, elem2 starting with the last element
    int head = 0;                                                                                                            int tail = length-1;
        while (Head < tail) {TempSum = Array[head] + array[tail];
            if (tempsum = = sum) {*elem1 = Array[head];
            *ELEM2 = Array[tail];
        return true;
        }else if (TempSum > Sum) {--tail;
     }else   {++head;
return false; }


Ideas:

Because the array is sorted in ascending order, all subsequent values must be larger than the preceding values.

Set two variables elem1 and elem2,elem1 to start backwards from the first number of arrays, elem2 to move forward from the last number of arrays.

The and of two variables are compared with the given number:

When and greater than the given number, the ELEM2 step forward, continue to compare;

When and less than the given number, elem1 a step backward, continue to compare;

Returns the current two variable values when and equals the given number, exiting the lookup.

Related Article

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.