【发布时间】:2018-11-17 22:43:47
【问题描述】:
我已经编写了两种方法的代码来找出 LeetCode 上字符串中的第一个唯一字符。
问题陈述: 给定一个字符串,找到第一个不重复的 字符并返回它的索引。如果不存在,则返回 -1。
示例测试用例:
s = "leetcode" 返回 0。
s = "loveleetcode",返回 2。
方法 1 (O(n))(如果我错了,请纠正我):
class Solution {
public int firstUniqChar(String s) {
HashMap<Character,Integer> charHash = new HashMap<>();
int res = -1;
for (int i = 0; i < s.length(); i++) {
Integer count = charHash.get(s.charAt(i));
if (count == null){
charHash.put(s.charAt(i),1);
}
else {
charHash.put(s.charAt(i),count + 1);
}
}
for (int i = 0; i < s.length(); i++) {
if (charHash.get(s.charAt(i)) == 1) {
res = i;
break;
}
}
return res;
}
}
方法 2 (O(n^2)):
class Solution {
public int firstUniqChar(String s) {
char[] a = s.toCharArray();
int res = -1;
for(int i=0; i<a.length;i++){
if(s.indexOf(a[i])==s.lastIndexOf(a[i])) {
res = i;
break;
}
}
return res;
}
}
在方法 2 中,我认为复杂度应该是 O(n^2),因为 indexOf 在这里执行 O(n*1)。
但是当我在 LeetCode 上执行这两种解决方案时,方法 2 的运行时间为 19 毫秒,方法 1 的运行时间为 92 毫秒。我很困惑;为什么会这样?
我认为 LeetCode 会针对最佳、最差和平均情况对小输入值和大输入值进行测试。
更新:
我知道对于某些 n
【问题讨论】:
-
您认为第二个解决方案是
n^2的原因是什么?indexOf和lastIndexOf都最多迭代字符串一次,因此字符串长度为 n 的总复杂度为 2*n。n^2意味着您为每个字符迭代一次字符串。 -
@daniu 这就是他在做什么:
for(int i=0; i<a.length;i++){ -
@Nivedita 请注意
s.indexOf(a[i])是...i。 -
@NathanHughes 对于 input="cc",如果我不使用 indexOf,代码将返回 1,而预期的答案是 -1,因为字符串没有唯一字符。
-
O() 衡量一个算法的可扩展性,而不是它的速度。
标签: java time-complexity big-o