面试题

本文提供了一个C++程序示例,该程序用于计算整数数组中连续三个数相加等于24的序列次数。通过遍历数组并累加指定长度内的元素来实现目标,最终返回符合条件的序列数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   http://topic.youkuaiyun.com/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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值