大神求助,算法问题

Tang_huawei 2012-02-17 09:34:35
找出1到某个数的含有1这个数的个数,例如18,含有1的就是 1,11,12,13,14,15,16,17,18
...全文
107 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
jiakai0419 2012-02-17
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 beowulf2005 的回复:]

这样扯法就没底了,
乘法和加法的复杂度都严格说都不一样。
讨论复杂度之前先要定标准,不然没法讨论。
[/Quote]

大哥,那你最起码不能说。

因为你掉个破函数复杂度就讲到o(n)了吧。

这个问题遍历一打眼复杂度就是o(n^2)

n个数,每个数看n位。

要抬杠的话,我就没办法了。
beowulf2005 2012-02-17
  • 打赏
  • 举报
回复
这样扯法就没底了,
乘法和加法的复杂度都严格说都不一样。
讨论复杂度之前先要定标准,不然没法讨论。
jiakai0419 2012-02-17
  • 打赏
  • 举报
回复
contains()
最终最终依靠的是这个函数

static int indexOf(char[] source, int sourceOffset, int sourceCount,
char[] target, int targetOffset, int targetCount,
int fromIndex) {
if (fromIndex >= sourceCount) {
return (targetCount == 0 ? sourceCount : -1);
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}

char first = target[targetOffset];
int max = sourceOffset + (sourceCount - targetCount);

for (int i = sourceOffset + fromIndex; i <= max; i++) {
/* Look for first character. */
if (source[i] != first) {
while (++i <= max && source[i] != first);
}

/* Found first character, now look at the rest of v2 */
if (i <= max) {
int j = i + 1;
int end = j + targetCount - 1;
for (int k = targetOffset + 1; j < end && source[j] ==
target[k]; j++, k++);

if (j == end) {
/* Found whole string. */
return i - sourceOffset;
}
}
}
return -1;
}


这个函数复杂度肯定不是o(1)

你给的那个方法不是o(n)
jiakai0419 2012-02-17
  • 打赏
  • 举报
回复
你有两点错误,

(1)直接遍历肯定不是o(n)

tmp.contains("1")源码你看过吗,这个方法肯定不是o(1)的复杂度。

所以n*!1 不是 o(n)

这个你应该能看懂。

(2)o(1)可能。
很多看似o(1)不可能,实际上数论就可以o(1)解决。

退一步说,如果我能打一个足够大的表。我也能o(1)。

别误导人。

LucEaspe 2012-02-17
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 jiakai0419 的回复:]
不要效率的话,有个O(n^2)的算法。

要效率,需要数论,有O(1)的算法。
[/Quote]o(1)是不可能的。
LucEaspe 2012-02-17
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 jiakai0419 的回复:]
不要效率的话,有个O(n^2)的算法。

要效率,需要数论,有O(1)的算法。
[/Quote]直接遍历 o(n)
LucEaspe 2012-02-17
  • 打赏
  • 举报
回复
class Main {
public static void main(String[] args) {
show(18);
}

private static void show(int n) {
String tmp = "";
for (int i = 1; i <= n; i++) {
// int 转 string
tmp = String.valueOf(i);
// 打印包含1的整数
if (tmp.contains("1")) {
System.out.print(i + ", ");
}
}
}
}
jiakai0419 2012-02-17
  • 打赏
  • 举报
回复
1 到 18

应该有10吧。
jiakai0419 2012-02-17
  • 打赏
  • 举报
回复
不要效率的话,有个O(n^2)的算法。

要效率,需要数论,有O(1)的算法。
LucEaspe 2012-02-17
  • 打赏
  • 举报
回复
这个不是很简单啊。o(n)

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧