数组查询效率高,增删效率低
链表查询效率低,增删效率高
数组的增删本质上是数组的拷贝,其用的是数组扩容的方法
System.arraycopy(src, srcPos, dest, destPos, length);
package 基本算法;
public class TestArraysCopy {
public static void main(String[] args) {
// ArraysCopy(2);
// extendRange();
insertElement(2, "qq");
}
// 删除元素,注意这里的index是从一算起的
public static String[] ArraysCopy(int index) {
String[] s1 = { "ds", "11", "ww" };
String[] s2 = { "11", "ww" };
// System.arraycopy(s1, 0, s1, 1, 1);
System.arraycopy(s1, index, s1, index-1, s1.length - index);
s1[s1.length - 1] = null;
for (String string : s1) {
System.out.print(string+",");
}
return s1;
}
// 数组扩容
public static String[] extendRange() {
String[] s1 = { "11", "22", "33" };
String[] s2 = new String[s1.length + (s1.length>>1)];
System.arraycopy(s1, 0, s2, 0, s1.length);
for (String q : s2) {
System.out.print(q+",");
}
System.out.println();
for (int i = 0; i < s2.length; i++) {
System.out.print(s2[i]+",");
}
return s2;
}
// 添加元素,这里又不需要index从一开始计数
public static String[] insertElement(int index,String x) {
String[] s1 = { "11", "22", "33" };
String[] s2 = new String[s1.length + 5];
System.arraycopy(s1, 0, s2, 0, s1.length );
System.arraycopy(s2, index, s2, index+1, s1.length - index);
s2[index]=x;
for (String qq : s2) {
System.out.println(qq);
}
return s2;
}
}
这些代码都是经过测试的,没问题,实现基本的增删功能