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)
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 + ", ");
}
}
}
}
很多看似o(1)不可能,实际上数论就可以o(1)解决。退一步说,如果我能打一个足够大的表。我也能o(1)。别误导人。
最终最终依靠的是这个函数 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)
大哥,那你最起码不能说。因为你掉个破函数复杂度就讲到o(n)了吧。这个问题遍历一打眼复杂度就是o(n^2)n个数,每个数看n位。要抬杠的话,我就没办法了。