C ++ searches for the first two numbers that appear in the sorted array and the value (requires the time complexity to be o (n ).

Source: Internet
Author: User

C ++ searches for the first two numbers that appear in the sorted array and the value (requires the time complexity to be o (n ).

# Include <iostream> using namespace std; // enter an array and a number that have been sorted in ascending order. // search for two numbers in the array, so that the sum of them is exactly the number entered. // The time complexity is O (n ). If there are multiple pairs of numbers and the sum is equal to the input number, output any one. // For example, input array 1, 2, 4, 7, 11, 15, and number 15. Because 4 + 11 = 15, 4 and 11 are output. Void Grial (int a [], int x, int y) {int j = X-1; int I = 0; while (a [j]> y) {j --;} while (I <j) {while (a [I] + a [j])> y) j --; if (a [I] + a [j])> y) {j --;} else if (a [I] + a [j]) <y) {I ++ ;} else {cout <a [I] <endl; cout <a [j] <endl; return ;}}} // note that the time complexity is o (n) at most. Find it from both sides. I don't know whether this algorithm is available or there is a better algorithm, but when I encountered this problem, I thought about it. // I am very happy to solve it. I hope to cheer up with you. int main () {int a [] = {1, 2, 3, 4, 5, 6, 7, 8, 9,100,300 0}; Grial (a, 11,3003 ); return 0 ;}

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.