/*******************************************************************
Copyright(c) 2016, Tyrone Li
All rights reserved.
*******************************************************************/
// 作者:TyroneLi
//
/*
Q1:
和爲s的兩個數字:
輸入一個遞增排序的數組和一個數字,在數組中找到兩個數,使得他們的和
剛好爲輸入的數字;如果有多對數字的和等於該數字,那麼輸出任意一對即可。
S1:
1. 在數組中隨機指向兩個數,如果這兩個數之和大於輸入的數字,那麼考慮在後面
一個比較大的數字上,將其往前挪,好讓兩者之和小一點;如果比輸入的數字小,
那麼可以考慮將前面那個數字往後挪一下,好讓兩者之和大一點。
Q2:
和爲s的連續正整數序列:
輸入一個正整數s,打印出所有的和爲s的連續正整數序列(至少含有兩個數)。
例如:
輸入:15
輸出:{1,2,3,4,5} [4,5,6] {7,8}
S2:
1. 借鑑題目一的思路,初始化兩個數,一個是1,另一個是2,如果該序列之和小於s,
那麼可以考慮加入更大的數,也就是第二個指針往前挪;如果該序列之和大於s,那
麼可以考慮去掉最小的數,也就是第一個指針往前挪。
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
void getSumOfNumPair(int*data, int length, long sum, int*num_1, int*num_2)
{
if(data == nullptr || length <= 0)
return;
int pAhead = 0;
int pBehind = length - 1;
while(pAhead < pBehind)
{
if(sum == (data[pAhead] + data[pBehind]))
{
*num_1 = pAhead;
*num_2 = pBehind;
break;
}else if(sum < (data[pAhead] + data[pBehind]))
{
pBehind--;
}else{
pAhead++;
}
}
}
void printLists(long small, long big)
{
for(long i = small; i <= big; ++i)
std::cout << i << " ";
std::cout << std::endl;
}
void getSumOfNumLists(long sum)
{
if(sum < 3)
return;
long small = 1;
long big = 2;
long curSum = small + big;
long mid = (1 + sum) / 2;
while(small < mid)
{
if(curSum == sum)
{
printLists(small, big);
}
while(curSum > sum && small < mid)
{
curSum -= small;
small++;
if(curSum == sum)
{
printLists(small, big);
}
}
big++;
curSum += big;
}
}
void test_1()
{
std::cout << "Test 1" << std::endl;
int data[] = {1,2,3,4,5,6,7,8,9,10};
for(auto e:data)
std::cout << e << " ";
std::cout << std::endl;
int num_1 = 0;
int num_2 = 0;
getSumOfNumPair(data, 10, 17, &num_1, &num_2);
std::cout << "sum : " << 17 << " num_1 : " << num_1 << " num_2 : " << num_2 << std::endl;
getSumOfNumLists(15);
}
void test_2()
{
std::cout << "Test 2" << std::endl;
int data[] = {1,2,3,4,5,6,7,8,9,10};
for(auto e:data)
std::cout << e << " ";
std::cout << std::endl;
int num_1 = 0;
int num_2 = 0;
getSumOfNumPair(data, 10, 20, &num_1, &num_2);
std::cout << "sum : " << 17 << " num_1 : " << num_1 << " num_2 : " << num_2 << std::endl;
getSumOfNumLists(99);
}
void test_3()
{
std::cout << "Test 3" << std::endl;
int*data = nullptr;
int num_1 = 0;
int num_2 = 0;
getSumOfNumPair(data, 0, 20, &num_1, &num_2);
std::cout << "sum : " << 17 << " num_1 : " << num_1 << " num_2 : " << num_2 << std::endl;
getSumOfNumLists(20);
}
void test_getSumOfNumPair()
{
test_1();
test_2();
test_3();
}
int main(int argc, char**argv)
{
test_getSumOfNumPair();
return 0;
}
劍指offer-和爲s的兩個數VS和爲s的正整數序列
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.