[英]What is the most efficient algorithm to find repeated elements in an array in time complexity O(n) and space complexity O(1)?
[英]Why is the space complexity for this algorithm to check if an array has all unique characters O(n)?
在“Cracking the Coding Interview”一书中,第一个练习说“实现一个算法来确定一个字符串是否具有所有唯一字符(不使用额外的数据结构)”。 和解决方案:
public static boolean isUniqueChars(String str) {
boolean [] char_set = new boolean[256];
for (int i = 0; i < str.length(); i++) {
int val = str.charAt(i);
if (char_set[val]) return false;
char_set[val] = true;
}
return true;
}
然后他们说“时间复杂度是 O(n),其中 n 是字符串的长度,空间复杂度是 O(n)”。
我不明白为什么空间复杂度是 O(n)。 数组char_set
具有恒定长度,与给定str
的长度无关。 对我来说,空间复杂度是 O(1)。
它的空间复杂度为O(1)
( \Theta(1)
),因为它比输入数组的大小多保留 256 个(常数)位。 此外,时间复杂度为O(1)
,因为在输入字符串中要检查 256 个字符,并且最多在字符串的第 256 个字符处检测到重复项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.