数组反转和扩缩容
数据反转
实现思想:数组对称位置的元素互换。
public static void arrayResever(int[] arr) { for (Object o : arr) { System.out.println(o); } System.out.println("-----------------"); for (int i = 0; i < arr.length/2; i++) { int temp = arr[i]; arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = temp; } //反转后遍历 for (Object o : arr) { System.out.println(o); } }
数组的扩容与缩容
数组的扩容
题目:现有数组 int[] arr = new int[]{1,2,3,4,5}; ,现将数组长度扩容1倍,并将10,20,30三个数据添加到arr数组中,如何操作?
public static void main(String[] args) { int[] arr = new int[]{1,2,3,4,5}; int[] newArr = new int[arr.length << 1]; for(int i = 0;i < arr.length;i++){ newArr[i] = arr[i]; } newArr[arr.length] = 10; newArr[arr.length + 1] = 20; newArr[arr.length + 2] = 30; arr = newArr; //遍历arr for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } }
数组的缩容
题目:现有数组 int[] arr={1,2,3,4,5,6,7}。现需删除数组中索引为4的元素。
for (int i = delIndex; i < arr.length - 1; i++) { arr[i] = arr[i + 1]; } arr[arr.length - 1] = 0; for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); }