由于经常使用一些集合方法,但是不太确定到底怎么快。而且做算法题的时候,可以用到这些就很方便,可以和https://blog.csdn.net/weixin_43139254/article/details/122365474?spm=1001.2014.3001.5501这个结合看
//时间复杂度是我感觉的
1.反转
//Collections.reverse(strings);时间复杂度O(N),大概就是min
public static void reverse(List<?> list) {
int size = list.size();
//size小于18或者是RandomAccess子类(较小,或者底层像arraylist一样通过下标获取事件复杂度是O(1)的就可以用swap)
if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
//交换首尾
swap(list, i, j);
} else {
// instead of using a raw type here, it's possible to capture
// the wildcard but it will require a call to a supplementary
// private method
//同样首尾交换,操作的list。。(>> 二进制向右移动一位,补0,因为是二进制所以就相当于/2)
ListIterator fwd = list.listIterator();
ListIterator rev = list.listIterator(size);
//min中位数取整相当于list.size/2
for (int i=0, mid=list.size()>>1; i<mid; i++) {
Object tmp = fwd.next();
fwd.set(rev.previous());
rev.set(tmp);
}
}
}
public static void swap(List<?> list, int i, int j) {
// instead of using a raw type here, it's possible to capture
// the wildcard but it will require a call to a supplementary
// private method
final List l = list;
//set,返回原有的值oldValue
l.set(i, l.set(j, l.get(i)));
}
2.排序
//Collections.sort();时间复杂度O(nlogn)+2n
default void sort(Comparator<? super E> c) {
//先转为array
Object[] a = this.toArray();
//排序,看数据大小,大于32用mergeSort ,小于用mini-TimSort。时间复杂度大概O(nlogn)
Arrays.sort(a, (Comparator) c);
ListIterator<E> i = this.listIterator();
//转回去
for (Object e : a) {
i.next();
i.set((E) e);
}
}
3.arrayList.removeAll(),retainAll
//时间复杂度O(n*m)
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
//不在里面都++,在里面就r++参考:https://blog.csdn.net/weixin_40841731/article/details/85263889
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++)
//把之后的设置为空
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
4.linkList.removeAll、retainAll
//感觉时间复杂度为O(n*m)
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
Iterator<?> it = iterator();
while (it.hasNext()) {
if (c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}