题目
删除数组中所有值为 x 的元素并压缩
思路
本题删除数组中所有等于 x 的元素,并把剩余元素紧凑到数组前部。 用读下标 r、写下标 w 扫描:若 a[r]!=x 就复制到 a[w++]。结束后有效长度为 w,按题面输出或返回。
解题分析
双引用:i 扫描,j 指向下一个写入位置,不等于 x 的留下。稳定版(保持相对顺序)与非稳定(交换到尾部)按题意选择。
完整程序
import java.io.*;
public class Main {
public static void main(String[] args) {
int n = 6;
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = 1;
int x = 2, j = 0;
for (int i = 0; i < n; i++) if (a[i] != x) a[j++] = a[i];
for (int i = 0; i < j; i++) System.out.print(a[i] + (i + 1 < j ? " " : "\n"));
}
}
运行示例
输出:
1 3 4