http://topic.csdn.net/u/20080905/02/3c98d86c-352e-4ca9-b4ed-e63159805407.html
Using any programming language you like, but without using advanced library functions:
Given an array of integers, count how many times any contiguous sequence of three numbers in the array adds up to the number '24'.
For example, in the following sequence:
8 9 7 4 5 6 11 13 0 4 8
The answer would be: 2, because "8 9 7" adds up to 24 and "11 13 0" adds up to 24.
and, in the following sequence:
12 6 6 8 10 5 4 15 2 7 10
The answer would be: 4.
来不及看数据结构的书了。以上是题目,求高效的算法。
请大家自由发挥~~~~
我的解答:
#include <iostream>
using namespace std;
// length:数组元素个数,sumSeq:和为多少(本例24), numSeq:序列个数(本例3)
int f(int arry[], int length, int sumSeq, int numSeq);
int main()
{
int a[]={8,9,7, 4, 5, 6, 11, 13, 0, 4, 8};
int b[]={12, 6, 6, 8, 10, 5, 4, 15, 2, 7, 10 };
int lengthA = sizeof(a)/sizeof(a[0]);
int lengthB = sizeof(b)/sizeof(b[0]);
cout < < f(a, lengthA, 24, 3) < <endl;
cout < < f(b, lengthB, 24, 3) < <endl;
}
int f(int arry[], int length, int sumSeq, int numSeq)
{
int count=0;
int sum =0;
int j=0;
int m_numSeq=0;
for(int i=0; i <length-2; ++i)
{
j=i;
sum=0;
m_numSeq = numSeq;
while(m_numSeq!=0)
{
sum += arry[j++];
if(sum > sumSeq)
break;
m_numSeq--;
}
if(sum==sumSeq)
{
count++;
}
}
return count;
}
面试题
最新推荐文章于 2024-10-11 23:09:56 发布