java - 我的算法检查两个字符串是否相互排列的时间和空间复杂度是否正确?
问题描述
/*
Returns true is the two strings are permutations of each other.
Time Complexity; O(nlog n) -> because of the java utils array sort
Space Complexity; O(1)
*/
public boolean isPermutationOptimized(String one, String two) {
if (one.length() != two.length()) {
return false;
}
return sort(one).equals(sort(two));
}
public String sort(String s) {
char[] c = s.toCharArray();
java.util.Arrays.sort(c);
return new String(c);
}
我相信时间复杂度是 O(nlogn) 因为 java.utils 数组排序和空间复杂度是恒定的。
解决方案
时间复杂度在平均和最坏情况下都是 O(nlogn)。Timsort(使用的排序算法)的空间复杂度需要额外的 O(n) 空间:它不是恒定复杂度,而是线性复杂度。一些参考资料:https ://ericmervin.medium.com/what-is-timsort-76173b49bd16
您的算法的复杂性与 Timsort 的复杂性相同,因为您使用了该算法的两倍。
推荐阅读
- opengl - 为什么图元是三角形时显示的图形,而图元是四边形时却消失了?
- android - Fragment stucks when, in OnCreateView, a Bitmap (path from SharedPreferences) is set by onBindViewHolder
- c# - 如何使用 AutoMapper 将嵌套的 json 对象映射到具有多个自定义类的 POCO?
- python - 分离手写扫描图像
- amazon-web-services - 反应原生 AWS S3 上传
- list - 如何过滤 csv 数据以在指定年份后删除数据?
- javascript - Css 和 Javascript 无法在 html 中加载
- python - 如果语句/条件参数在 Geany (PYTHON) 中不起作用
- python - tabula vs camelot 用于从 PDF 中提取表格
- java - GraphAPI 在创建新组后立即创建新的 MSTeam 失败并出现 404