我需要检查一个数组是否是另一个更大数组的子数组。 (在句子(数组)中查找单词(子数组))。
我需要在递归算法中做到这一点。 运行时间将为 log(n)。
数组:
char[] sentence = {'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'};
char[] word = {'l', 'l', 'o', 'w', 'o', 'r'};
char [] word = {'t', 'n' , 'p'};
我的代码:
static boolean wordFinder(char[] arr, char[] arr2, int l, int i) {
if (i == arr2.length - 1) {
return true;
}
if (arr[l] == arr2[i]) {
return wordFinder(arr, arr2, l + 1, i + 1);
}
if (l == arr.length - 1) {
return false;
}
return wordFinder(arr, arr2, l + 1, 0);
}
第三个数组仅用于检查代码。 (代码可以工作,只需要知道运行时间)。
最佳答案
听起来您有兴趣测试一段代码的运行时间。为此,只需记录之前和之后的时间(以毫秒为单位),然后将两者相减。
long start_time = System.currentTimeMillis();
...
...
long end_time = System.currentTimeMillis();
System.out.println("Code completed in " + (end_time - start_time) + "milliseconds.");
还有用于纳秒的 System.nanoTime()
。
关于java - 如何查看java程序的运行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56541461/