去除数组中的重复元素

去除数组中的重复元素

例如:输入1 1 5 1 6 2 1 2 3
输出:1 2 3 5 6

思路:

  • 对数组排序;
  • 设置快慢指针,一先一后来筛选重复元素。

主要代码如下:

		int[] newres = new int[n] ;
		for(int i = 0;i<newres.length;i++) {
			newres[i] = -1;
		}
		Arrays.sort(res);
		int l = 1;			//快指针
		int m = 0;			//慢指针
		int z = 0;
		while(l<res.length) {
			if(res[m] == res[l]  ) {
					l++;   //相等时,快指针加一,直到寻找到不相等的元素;
				}else {
					newres[z++] = res[m];//不相等时,将慢指针的值赋值到新数组中保存;
					m = l;//更新慢指针的值,让慢指针更上快指针的“小步伐”
					l++;//更新快指针的值,继续寻找下个不相等的值;
				}
			}
		newres[z] = res[m]//为防止快指针越界,所以将边界值另做处理;
		for(int i :newres) {
			if(i != -1)
				System.out.print(i + " ");
		}

完整代码:

package lanqiaobei;

import java.util.Arrays;
import java.util.Scanner;

public class quchong {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner inpScanner = new Scanner(System.in);
		int n = inpScanner.nextInt();
		int[] res = new int[n];
		for(int i = 0;i<n;i++) {
			res[i] = inpScanner.nextInt();
		}
		quchong(n,res);
	}
	public static void quchong(int n,int[] res) {
		int[] newres = new int[n] ;
		for(int i = 0;i<newres.length;i++) {
			newres[i] = -1;
		}
		Arrays.sort(res);
		int l = 1;
		int m = 0;
		int z = 0;
		while(l<res.length) {
				if(res[m] == res[l]  ) {
					l++;
				}else {
					newres[z++] = res[m];
					m = l;
					l++;
				}
			}
		newres[z] = res[m];
		for(int i :newres) {
			if(i != -1)
				System.out.print(i + " ");
		}
	}
}

你可能感兴趣的:(去除数组中的重复元素)