[Sword refers to Offer learning] [interview question 41: two numbers vs for s and a continuous positive number sequence for s], sword refers to offer

Source: Internet
Author: User

[Sword refers to Offer learning] [interview question 41: two numbers vs for s and a continuous positive number sequence for s], sword refers to offer
Question 1: enter an incremental sorting array and a number s to search for two numbers in the array. The sum of them is exactly s. If the sum of multiple pairs of numbers is equal to s, output any pair.Example

For example, input arrays {1, 2, 4, 7, 11, 15} and numbers 15. Because 4 + 11 = 15, output 4 and 11.

Solutions

First, we select two numbers in the array. If their sum is equal to the input s, we will find the two numbers. What if the sum is less than s? We want the sum of the two numbers to be larger. Since the array has already been sorted, we can consider selecting a number after a smaller number. Because the numbers listed at the end are larger, and the numbers listed at the end are also larger, they may be equal to the input number s. Similarly, when the two numbers and the two numbers are greater than the input numbers, we can select the number before the larger number, because the number before the array is smaller.

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. ** @ Param data * @ param sum * @ return */public static List <Integer> findNumbersWithSum (int [] data, int sum) {List <Integer> result = new ArrayList <> (2); if (data = null | data. length <2) {return result;} int ahead = data. length-1; int behind = 0; long curSum; // calculates the sum of values. taking long is used to prevent result overflow while (behind <ahead) {curSum = data [behind] + data [ahead]; if (curSum = sum) {result. add (data [behind]); result. add (data [ahead]); break;} else if (curSum <sum) {behind ++;} else {ahead -- ;}} return result ;}
Question 2: enter a positive number s to print all continuous positive numbers (at least two numbers) for s ). Example

For example, if the input is 15, because 1 + 2 + 3 + 4 + 5 = 4 + 5 + 6 = 7 + 8 = 15, 3 consecutive sequences 1 ~ 5, 4 ~ 6 and 7 ~ 8.

Solutions

Two numbers small and big are used 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 big is greater than s, we can remove a smaller value from the sequence, that is, increase the value of small. If the sum of values from small to big is smaller than s, we can increase big to include more numbers. Because this sequence must have at least two numbers, we keep increasing small to (1 + s)/2.
For example, we first initialize small to 1 and big to 2 for all consecutive sequences whose sum is 9. In this case, the sequence between small and big is {1, 2}, and the sequence is 3, less than 9. Therefore, we need to let the sequence contain more numbers. We increase big by 1 to 3, and the sequence is {I, 2, random. Since the sum of the sequences is 6 and is still less than 9, we will increase the number of big values to 4, and the sequence between small and big will become {l, 2, 3, 4 }. Since the column and 10 are greater than 9, we need to delete some numbers from the sequence, so we increase small to 2, and the obtained sequence is {2, 3, 4 }, the sum of sequences and values of E is 9. We found the first continuous sequence for 9 and printed it out. Next we will add big, repeat the previous process, and find the continuous sequence {4, 5} with the second sum of 9 }.

Code Implementation
public static List<List<Integer>> findContinuousSequence(int sum) {    List<List<Integer>> result = new ArrayList<>();    if (sum < 3) {        return result;    }    int small = 1;    int big = 2;    int middle = (1 + sum) / 2;    int curSum = small + big;    while (small < middle) {        if (curSum == sum) {            List<Integer> list = new ArrayList<>(2);            for (int i = small; i <= big; i++) {                list.add(i);            }            result.add(list);        }        while (curSum > sum && small < middle) {            curSum -= small;            small++;            if (curSum == sum) {                List<Integer> list = new ArrayList<>(2);                for (int i = small; i <= big; i++) {                    list.add(i);                }                result.add(list);            }        }        big++;        curSum += big;    }    return result;}
Complete code
Public class Test41 {/*** 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. ** @ Param data * @ param sum * @ return */public static List <Integer> findNumbersWithSum (int [] data, int sum) {List <Integer> result = new ArrayList <> (2); if (data = null | data. length <2) {return result;} int ahead = data. length-1; int behind = 0; long curSum; // calculates the sum of values. taking long is used to prevent result overflow while (behind <ahead) {curSum = data [behind] + data [ahead]; if (curSum = sum) {result. add (data [behind]); re Sult. add (data [ahead]); break;} else if (curSum <sum) {behind ++;} else {ahead -- ;}} return result ;} /*** Question 2: enter a positive number s to print all continuous positive number sequences (at least two numbers) for s ). * @ Param sum * @ return */public static List <Integer> findContinuousSequence (int sum) {List <Integer> result = new ArrayList <> (); if (sum <3) {return result;} int small = 1; int big = 2; int middle = (1 + sum)/2; int curSum = small + big; while (small <middle) {if (curSum = sum) {List <Integer> list = new ArrayList <> (2); for (int I = small; I <= big; I ++) {list. add (I);} result. add (list) ;}while (curSum> sum & small <middle) {curSum-= small; small ++; if (curSum = sum) {List <Integer> list = new ArrayList <> (2); for (int I = small; I <= big; I ++) {list. add (I);} result. add (list) ;}}big ++; curSum + = big;} return result ;}public static void main (String [] args) {test01 (); System. out. println ("---------------"); test02 ();} private static void test01 () {int [] data1 = {1, 2, 4, 7, 11, 15}; System. out. println (findNumbersWithSum (data1, 15); int [] data2 = {1, 2, 4, 7, 11, 16}; System. out. println (findNumbersWithSum (data2, 17); int [] data3 = {1, 2, 4, 7, 11, 16}; System. out. println (findNumbersWithSum (data3, 10);} public static void test02 () {System. out. println (findContinuousSequence (1); System. out. println (findContinuousSequence (3); System. out. println (findContinuousSequence (4); System. out. println (findContinuousSequence (9); System. out. println (findContinuousSequence (15); System. out. println (findContinuousSequence (100 ));}}
Running result

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.