Leetcode 新题 number-of-digit-one 求解

2015-07-07 23:10:42 +08:00
 plantparknet
https://leetcode.com/problems/number-of-digit-one/

先转换成字符串,然后看1出现的次数。。。好愚蠢的办法。。。结果提示Runtime Err

class Solution:
# @param {integer} n
# @return {integer}
def countDigitOne(self, n):
numStr = ""
for i in range(1,n+1):
numStr = numStr + str(i)
result = 0
for n in numStr:
if n == "1":
result = result + 1
return result
4068 次点击
所在节点    Python
24 条回复
bengol
2015-07-07 23:31:27 +08:00
好像是编程之美上的题吧
msg7086
2015-07-07 23:32:13 +08:00
花点时间想想更高效率的算法不行么?
20015jjw
2015-07-07 23:42:28 +08:00
class Solution:
# @param {integer} n
# @return {integer}
def countDigitOne(self, n):
return sum((1 for i in range(n+1) if '1' in str(i)))

如果用lz的办法死算,是会超时的...
20015jjw
2015-07-07 23:42:47 +08:00
@20015jjw 这个就是死算的办法...
msg7086
2015-07-07 23:45:47 +08:00
@20015jjw 不是 1 if '1' in str(i),而是count。
yangqi
2015-07-08 00:02:29 +08:00
没看Hint说的是注意overflow么
20015jjw
2015-07-08 00:05:45 +08:00
@msg7086 啥?这个结果跑出来是对的啊.. 就是超时..
msg7086
2015-07-08 00:36:10 +08:00
@20015jjw count_digit_one(2147483647) == 2971027783 你看看你是不是这结果。
20015jjw
2015-07-08 00:46:38 +08:00
@msg7086 - - 目测是 但是要跑两年 因为这个办法是死算的 - - 你换个小于100k的数呢
msg7086
2015-07-08 00:53:34 +08:00
@20015jjw count_digit_one(76543) == 41015
20015jjw
2015-07-08 00:57:01 +08:00
@msg7086 啊哈懂了 xD 看错题了xDDDDD 谢谢!
>>> sum((1 for i in range(76543+1) if '1' in str(i)))
33179
>>> sum((str(i).count('1') for i in range(76543+1) if '1' in str(i)))
41015
mickeyandkaka
2015-07-08 00:57:02 +08:00
递归,举个例子 51234 = 50000 + 1000+ 200+ 30 + 4
低位可以对高位做贡献,复杂度log(n)

数位dp很容易做出来。部分代码
long long dfs(int pos, bool bound)
{
if(pos == -1) return 0;
if(!bound && ~dp[pos]) return dp[pos];

int end = bound ? dig[pos]-'0' : 9;
long long ret = 0;
for(int i=0; i<=end; i++)
{
ret += dfs(pos-1, bound && i == end);
if(i == 1)
{
if(bound && i == end) ret += q[pos] + 1;
else ret += p[pos];
}
}
if (!bound) dp[pos] = ret;
return ret;
}
msg7086
2015-07-08 01:09:40 +08:00
@20015jjw 楼主这个应该是爆内存了。随便就要吃掉2G内存。
xhuuanniqege
2015-07-08 01:12:37 +08:00
数位dp
IwfWcf
2015-07-08 01:17:00 +08:00
msg7086
2015-07-08 01:47:03 +08:00
40 / 40 test cases passed.
Status: Accepted
Runtime: 72 ms
Submitted: 1 hour, 3 minutes ago

https://gist.github.com/msg7086/4477fb824f1d7968178c
20015jjw
2015-07-08 06:06:28 +08:00
@msg7086 下学期学DP... 请问这是DP嘛...
msg7086
2015-07-08 07:38:34 +08:00
@20015jjw 我的代码并不是。
20015jjw
2015-07-09 05:33:42 +08:00
10 minutes ago Accepted 44 ms (submitted without the doctest) python

https://gist.github.com/20015jjw/74ab03818741aaa0e7bb
plantparknet
2015-07-09 12:44:39 +08:00
@20015jjw Great!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/204070

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX