For an interview, the sum of two numbers is a certain number, and the number of consecutive numbers is equal to a certain number.

Source: Internet
Author: User

For an interview, the sum of two numbers is a certain number, and the number of consecutive numbers is equal to a certain number.

  Question 1EnterIncrementSort the array and number s, and find two numbers in the array so that their sum is exactly s. If there are multiple pairs of numbers and the sum is equal to s, the outputAny pairYou can.

Obviously, what you can think of soon is to makeUsing the brute force method (O (n2 ))First, fix a number, and then judge whether the remaining n-1 digits and their sum are equal to s. This efficiency is obviously a little low. We can use the following fast method, time complexity O (n ).

  Ideas: We use the start position and end position of the two record arrays to obtain the sum of the two numbers starting from the end of the array,

If the sum of two numbers isGreaterIf we need to request the number s, the next record is moved forward to one position (because the order is sorted, the first place is moved forward, which is equivalent to reducing the number of values) Before making a judgment,

If the sum of two numbers isLessIf we require the number s, the first position record is moved to the next position (because the order is sorted, and the last position is shifted to the next position, which is equal to the increase of the value) Before making a judgment,

    UntilLocate or overlap the position record later or earlier.

Code Implementation:

/*** Enter an incremental sorting array and a number s, and search for two numbers in the array so that their sum is exactly s. If there are multiple pairs of numbers and the sum is equal to s, output any pair. Because java can only return one value *, the returned value is true or false, or you can change it to an array to return the two numbers found. In this case, the returned value is true or false. If it is found, the returned value is printed! * @ Param data the incremental array to be searched * @ param length array length * @ param sum and * @ return: whether the search is successful! */Public static boolean FindNumberWithSum (int data [], int length, int sum) {boolean found = false; if (length <1) {return found ;} int ahead = length-1; // subscript Of a large number int behind = 0; // subscript of a small number while (ahead> behind) {long curSum = data [ahead] + data [behind]; if (curSum = sum) {System. out. println ("search successful! Two numbers: "+ data [ahead] +", "+ data [behind]); break;} else if (curSum> sum) {ahead --;} else {behind ++;} return found ;}

 

 

Test:

public static void main(String[] args)    {        int[] arr = {1,2,4,7,11,15};                FindSumEqualNum.FindNumberWithSum(arr,arr.length,15);    }

 

 

Result:

Search successful! Two numbers: 11,4

 

 

 

Question 2Input a positive number s to print allContinuous positive numberA sequence (containing at least two numbers ). For example, input 15, because 1 + 2 + 3 + 4 + 5 = 4 + 5 + 6 = 7 + 8 = 15,Therefore, three consecutive sequences are printed ~ 5, 4 ~ 6. 7 ~ 8

Similarly, the brute force method can solve this problem, that is, from 1, continue accumulating until the obtained value is equal to or less than the accumulated value. Equal means finding, if the value <accumulated value is not found, the initial value is added and the Calculation continues. It can be seen that this will repeat the calculation of the intermediate addition many times. We can use the following method to quickly obtain the result and minimize the accumulation of duplicates.

  Ideas: Use two numbers small and big to represent the minimum and maximum values of the sequence respectively. First, initialize small to 1 and big to 2,

If the sum of the sequences from small to bigGreaterS, we can subtract a smaller value from the sequence, that is, increase the small value.

If the sum of the sequences from small to bigLessS. We can increase the big value so that the sequence contains more numbers.

Because the sequence has at least two numbers, we keep increasing small to (1 + s)/2.So far.

Code Implementation:

Output the number of consecutive records found

/*** Output all numbers from small to big * @ param small start number [included] * @ param big end number [included] */public static void PrintContinuousSequence (int small, int big) {for (int I = small; I <= big; I ++) {System. out. print (I + ",");} System. out. println ("");}

 

Core functions

/*** Input a positive number s to print all continuous positive number sequences (including at least two numbers) for s) * @ param sum and */public static void FindSeriousSequence (int sum) {if (sum <3) {return;} int small = 1; int big = 2; int middle = (1 + sum)/2; int curSum = small + big; while (small <middle) {if (curSum = sum) {PrintContinuousSequence (small, big) ;}while (curSum> sum & small <middle) {curSum-= small; small ++; if (curSum = sum) {PrintContinuousSequence (small, big) ;}} big ++; curSum + = big ;}}

 

 

Test

public static void main(String[] args)    {        FindSeriousSequence(15);    }

 

 

Result:

1,2,3,4,5,4,5,6,7,8,

 

Thank you for your patience!

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.