我写了下面的代码来检测字符串中的第一个重复字符.
public static int detectDuplicate(String source) {
boolean found = false;
int index = -1;
final long start = System.currentTimeMillis();
final int length = source.length();
for(int outerIndex = 0; outerIndex < length && !found; outerIndex++) {
boolean shiftPointer = false;
for(int innerIndex = outerIndex + 1; innerIndex < length && !shiftPointer; innerIndex++ ) {
if ( source.charAt(outerIndex) == source.charAt(innerIndex)) {
found = true;
index = outerIndex;
} else {
shiftPointer = true;
}
}
}
System.out.println("Time taken --> " + …Run Code Online (Sandbox Code Playgroud) 数组是这样声明的:
int array[M], O(1)in space 还是O(n)? 其中 M 是某个固定值。对我来说O(n)是有道理的,因为它不仅仅是一个变量,而是一个完整的数组。但是我认为这可能是O(1)因为我们有一个固定的大小并且它没有改变!