我有一个程序,它使用 HashSet 简单地删除字符数组的重复元素。
这是我的程序:
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MainClass {
public static void main(String[] arg) {
double sT = System.nanoTime();
Character[] data = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b',
'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z' };
Set<Character > uniqueSet = new HashSet<Character>(Arrays.asList(data));
Character[] strArr = new Character[uniqueSet.size()];
uniqueSet.toArray(strArr);
for(Character str:strArr){
System.out.println(str);
}
System.out.println(System.nanoTime() - sT);
}
}
它给出了所需的输出。但问题是执行时间。有什么方法可以在我的程序中实现以减少其执行时间?
最佳答案
由于您可以拥有的不同类型的元素非常少,您可以轻松地使用一个简单的数组而不是哈希集(一种类似于集合或计数排序的方法)。如果您只关心非大写英文字母,请声明一个数组 boolean met[26];
,如果您需要能够支持所有字符,请使用 boolean met[256];
.
然后遍历数组,如果它的 met
值为 false,则只向结果添加一个字符。将字符添加到结果时,不要忘记将其标记为已使用。
不涉及散列,因此性能更好。
编辑:似乎我的意思有些困惑,我将尝试添加一个代码示例
boolean met[] = new boolean[256]; // Replace 256 with the size of alphabet you are using
List<Character> res = new ArrayList<Character>();
for(Character c:data){
int int_val = (int)c.charValue();
if (!met[int_val]) {
met[int_val] = true;
res.add(c);
}
}
// res holds the answer.
关于java - 减少执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14378143/