LeetCode 829. Consecutive Numbers Sum--笔试题--C++解法

本文详细解析了LeetCode 829题连续整数求和的多种C++解法,包括暴力穷举、等差数列应用及优化算法,探讨了如何有效计算一个正整数可以表示为连续正整数之和的方式数量。

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

LeetCode 829. Consecutive Numbers Sum–笔试题–C++解法


LeetCode题解专栏:LeetCode题解
LeetCode 所有题目总结:LeetCode 所有题目总结
大部分题目C++,Python,Java的解法都有。


题目地址:Consecutive Numbers Sum - LeetCode


Given a positive integer N, how many ways can we write it as a sum of consecutive positive integers?

Example 1:

Input: 5
Output: 2
Explanation: 5 = 5 = 2 + 3

Example 2:

Input: 9
Output: 3
Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4

Example 3:

Input: 15
Output: 4
Explanation: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5

Note: 1 <= N <= 10 ^ 9.


这道题目是2019-9-10的XX笔试原题,可惜我没有事先看到,听别人在牛客网上说才知道的。

这道题目最容易想到的解法就是暴力穷举,时间复杂度O(N^2),肯定超时。
使用等差数列,可以快一些:
C++解法如下:

class Solution {
public:
    int consecutiveNumbersSum(int N) {
        int result = 1;
        int a = N;
        int temp;
        for (int i = 1; i < a / 2 + 1; i++) {
            for (int j = i + 1; j <= a - i; j++) {
                temp = (i + j) * (j - i + 1) / 2;
                if (temp == a) {
                    result += 1;
                    break;
                } else if (temp > a) {
                    break;
                }
            }
        }
        return result;
    }
};

但上面的做法会超时,换一个思路,首项是x,有m项,那么[x + (x + (m-1))]m / 2->x*m+m*(m-1)/2=n,只要遍历m从1到sqrt(n)即可。

C++解法如下:

class Solution {
public:
    int consecutiveNumbersSum(int N) {
        int ans = 0;
        for (int m = 1;; m++) {
            int m_x = N - m * (m - 1) / 2;
            if (m_x <= 0)
                break;
            if (m_x % m == 0)
                ans++;
        }
        return ans;
    }
};

更快的C++解法如下:

class Solution {
public:
    int consecutiveNumbersSum(int N) {
        int sum = 0, ans = 0;
        for(int i = 1; sum < N; i++) {
            sum += i;
            if (((N-sum) % i) == 0)
                ans++;
        }
        return ans;
    }
};

思路是:
let N = k + (k+1) + (k+2) + (k+3) + … + (k+i-1) = ik + (1+2+3+… + i-1)
let sum(i) = (1+2+3+…+i-1), then we have
N = sum(i) + i
k ==>i*k = N - sum(i)
Which means: for each i, we can calculate N-sum(i). If N-sum(i) can be divided by i, there is an answer with length i.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值