diff --git a/README.md b/README.md index 96d54a2..7c165d0 100644 --- a/README.md +++ b/README.md @@ -297,5 +297,6 @@ My LeetCode solutions with Chinese explanation. 我的LeetCode中文题解。 | 661 |[Image Smoother](https://leetcode.com/problems/image-smoother)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/661.%20Image%20Smoother.md)|Easy| | | 665 |[Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/665.%20Non-decreasing%20Array.md)|Easy| | | 714 |[Best Time to Buy and Sell Stock with Transaction Fee](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/714.%20Best%20Time%20to%20Buy%20and%20Sell%20Stock%20with%20Transaction%20Fee.md)|Medium| | +| 829 |[Consecutive Numbers Sum](https://leetcode.com/problems/consecutive-numbers-sum/)|[C++](solutions/829.%20Consecutive%20Numbers%20Sum.md)|Hard| | | 905 |[Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/)|[C++](solutions/905.%20Sort%20Array%20By%20Parity.md)|Easy| | | 946 |[Validate Stack Sequences](https://leetcode.com/problems/validate-stack-sequences/)|[C++](solutions/946.%20Validate%20Stack%20Sequences.md)|Medium| | diff --git a/solutions/829. Consecutive Numbers Sum.md b/solutions/829. Consecutive Numbers Sum.md new file mode 100644 index 0000000..6283943 --- /dev/null +++ b/solutions/829. Consecutive Numbers Sum.md @@ -0,0 +1,33 @@ +# [829. Consecutive Numbers Sum](https://leetcode.com/problems/consecutive-numbers-sum/) + +# 思路 + +给定正整数N,问N能写成多少种连续正整数之和,比如9可以写成 4+5,或者2+3+4。 + +我们假设把N拆分成k个连续的数之和,并设最小的那个数是m,则我们有: + +|k| 1 | 2 | 3 | 4 | ... | K | +|---|:-:|:-:|:-:|:-:|:-:|:-:|:-:| +|连续序列|m|m,m+1|m,m+1,m+2|m,m+1,m+2,m+3|...|m,m+1,m+K-1| +|满足关系|N=m|N = 2m+1| N = 3m+3| N = 4m+6|...| N = Km + f(k) | + +其中 f(k) = 1 + 2 +...+ k-1。 + +有了这个规律我们就知道了如果 `(N - f(k)) % k == 0`则说明可以拆成k个连续的数,那我们就可以从 k=1 不断增大k直到不满足`N <= f(k)`即可。 + +由于 f(k) = 1 + 2 +...+ k-1 = (k*k-1)/2。所以k最大为 sqrt(2N) 向下取整。所以时间复杂度为O(sqrt(N))。 + +# C++ +``` C++ +class Solution { +public: + int consecutiveNumbersSum(int N) { + int res = 0, k = 1, fk = 0; + while(N > fk){ + if((N - fk) % k == 0) res++; + fk += (k++); + } + return res; + } +}; +```