【发布时间】:2016-02-16 04:16:04
【问题描述】:
所以我最近一直在研究与算法的运行时复杂性有关的所有内容,并想学习如何改变它们以在 n 的规模增加时提高效率,所以基本上我的目标是学习如何使事情 O (log n)。心想,我知道我这个小时可以做一个很好的小项目,那就是创建一个字谜检查器。
我翻阅了一些 SO 帖子,看到有人评论说,如果您将字母表中的每个字母都分配给一个数字,那么它可以成为 log n:
final Map<Character, Integer> map;
String str = "hello";
String check = "olleh";
map = new HashMap<>();
map.put('a', 2);
map.put('b', 3);
map.put('c', 4);
map.put('d', 7);
map.put('e', 11);
map.put('f', 13);
map.put('g', 17);
map.put('h', 19);
map.put('i', 23);
map.put('j', 29);
map.put('k', 31);
map.put('l', 37);
map.put('m', 41);
map.put('n', 43);
map.put('o', 47);
map.put('p', 53);
map.put('q', 59);
map.put('r', 61);
map.put('s', 67);
map.put('t', 71);
map.put('u', 73);
map.put('v', 79);
map.put('w', 83);
map.put('x', 89);
map.put('y', 97);
map.put('z', 101);
然后我创建了方法:
public static boolean isAnagram(String s, String check,Map<Character, Integer> map) {
int stringTotal = 0;
int checkTotal = 0;
for(char ch: s.toCharArray()){
int i = map.get(ch);
stringTotal += ch;
}
for(char ch: check.toCharArray()){
int i = map.get(ch);
checkTotal +=ch;
}
if (stringTotal == checkTotal){
return true;
}
return false;
}
我相信这个方法是 O(n^2),因为它有两个独立的循环,我想不出创建这个 O(log n) 方法背后的逻辑。
任何指针都会很棒
【问题讨论】:
-
仅供参考,两个独立的循环并不意味着 O(N^2)。想一想......你正在经历一个长度为 N 的数组两次(2N)。预先快速检查以确保您不会将时间花在昂贵的操作上,即在您的逻辑之前确保字符串的长度相等。
-
哦,是的,当然@Tgsmith61591 感谢您指出这一点