[英]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.