最近项目中出现一个需求类似于"查询有序数组中所有重复的元素",一开始的想法是使用两次for循环遍历,但是这样的话运算量是几何级的(假设数组长度为len,则需运算len*len次才能得到结果),速度方面令人很不满意,于是在初步演算之后,实现了一次for循环即得到结果,代码如下:
public class DuplicateNum {
public static void main(String[] args) {
long start = System.currentTimeMillis();
System.out.println("start");
//源数组
int source[] = { 1, 2, 2, 3, 3, 3, 4, 5, 5, 5, 5, 5, 5, 6 };
//目标集合,将所有重复元素放入此集合中
List<Integer> target = new ArrayList<Integer>();
//标识符,用于在循环中标识上次比较的结果
boolean flag = false;
for (int i = 0; i < source.length - 1; i++) {
if (source[i + 1] == source[i]) {
target.add(source[i]);
flag = true;
System.out.println(source[i]);
} else {
//如果上次比较结果(source[i] == source[i-1])为真
if (flag) {
target.add(source[i]);
flag = false;
System.out.println(source[i]);
}
}
}
System.out.println("本次遍历消耗了:" + (System.currentTimeMillis() - start)
+ "毫秒!");
}
}