一个关于数组的小算法,谁能给段代码?
下面这是一个数组:int[] arr = {0,1,1,1,2,3,4,4,5,6,7,7,7,7,8};
要求得到一个不含重复元素的数组。
希望大家能写个实现代码!!!
闲来无事,写几个玩玩:
方法一:
import java.util.*;/**
* By [url=http://eastsun.javaeye.com]Eastsun[/url]
*/
public class Differ{
public static int[] differ(int[] array){
Set<Integer> set =new HashSet<Integer>();
for(int i: array) set.add(i);
int[] newArr =new int[set.size()];
int index =0;
for(int i: set) newArr[index++] =i;
return newArr;
}
public static void main(String[] args){
int[] arr={0,1,1,1,2,3,4,4,5,6,7,7,7,7,8};
int[] result =differ(arr);
for(int i: result) System.out.print(i+\",\");
}
}
import java.util.*;
/**
*By [url=http://eastsun.javaeye.com]Eastsun[/url]
*/
public class Differ{
public static int[] differ(int[] arr){
int[] newArr =Arrays.copyOfRange(arr,0,arr.length);
Arrays.sort(newArr);
int count =0, preValue =newArr[0]+1;
for(int index=0,n=0;index<newArr.length;index++){
int curValue =newArr[index];
if(preValue!=curValue){
newArr[count++] =curValue;
preValue =curValue;
}
}
return Arrays.copyOfRange(newArr,0,count);
}
public static void main(String[] args){
int[] arr={7,1,4,1,2,3,4,1,5,6,7,7,7,0,8};
int[] result =differ(arr);
for(int i: result) System.out.print(i+\",\");
}
}