去除数组中重复元素

方法一:使用容器

View Code
 1 import java.util.List;
2 import java.util.ArrayList;
3 public class DeleteRepeat
4 {
5 public static void main(String[] args)
6 {
7 int[] a={1,2,34,5,6,7,852,1,12,234,7,52,7,452,7,54,6,8,7,9};
8 List<Integer> list=new ArrayList<Integer>();
9 for(int i=0;i<a.length;i++)
10 {
11 if(list.indexOf(a[i])==-1)
12 {
13 list.add(a[i]);
14 }
15 }
16 Integer[] oj=(Integer[])list.toArray(new Integer[0]);
17 for(Integer in:oj)
18 System.out.print(in+" ");
19
20
21 }
22 }

方法二:不使用容器,顺序比较

View Code
 1 public class DeleteRepeat01
2 {
3 public static void main(String[] args)
4 {
5 int[] a={1,2,34,5,6,7,852,1,12,234,7,52,7,452,7,54,6,8,7,9};
6 int len=a.length;
7 int strLen=len;
8 for(int i=0;i<len;i++)
9 {
10 for(int j=i+1;j<len;j++)
11 {
12 if(a[i]!=-1&&a[i]==a[j])
13 {
14 a[j]=-1;//去除数组中重复元素,并给定了一个特定的数值
15 strLen--;
16 }
17 }
18 }
19 int[] temp=new int[strLen];
20 int j=0;
21 for(int i=0;i<a.length;i++)
22 {
23 if(a[i]!=-1)//判断是否为给定的数值
24 {
25 temp[j]=a[i];
26 j++;
27 }
28 }
29 for(int sa:temp)
30 {
31 System.out.print(sa+" ");
32 }
33 }
34 }




原文地址:https://www.cnblogs.com/xiongyu/p/2256841.html