forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
57b62db
commit 8e19e9a
Showing
1 changed file
with
14 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
### 1103.Distribute-Candies-to-People | ||
|
||
这道题不难,用全程模拟的方法,代码可以很短,但是效率不是很高。一种提升效率的方法就是计算出这些糖能够发几轮(比如说k轮),那么前k轮中每个人可以得到的糖的数目就可以直接用数列求和算出来。 | ||
``` | ||
第一轮:1,2,3,..., N | ||
第二轮:1+N,2+N,3+N,..., 2N | ||
第三轮:1+2N,2+2N,3+2N,..., 3N | ||
... | ||
``` | ||
可见,完整的第k轮,总共需要发放糖果数目是```(1+N)*N/2+N*N*k```。将candies的数目逐轮减去这个数目,就可以知道k是几。 | ||
|
||
然后,对于前k轮,第i个人得到的糖果数目也就是个等差数里:```i+1, i+1+N, i+1+2N, ..., i+1+(k-1)*N```,求和之后就是```(i+1+i+1+(k-1)*N)*k/2```. | ||
|
||
至于剩下糖果的零头,就再走一遍即可。此时是第k+1轮,第0个人需要1+k*N个糖果,第1个人需要2+k*N个糖果,...。一路分发,直至看糖果最终在哪个人手里用完。 |