Java数组去重,并将重复的数字改为0放置数组的末尾
如{1,1,2,4,5}
运行后{1,2,4,5,0}
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
int arr[] = new int[] { 1, 1, 2, 4, 5 };
List<Integer> collection = Arrays.stream(arr).distinct().boxed().collect(Collectors.toList());
for (int i = 0; i < arr.length - collection.size(); i++) {
collection.add(0);
}
System.out.println(collection);
}
}
有用的话采纳下哦~
1.找出数组中重复的数字
2.有几个重复的数字,就在数组末尾添加几个0
所以难点在数组去重上,这就简单了
1.将数组中的数据放到set集合中,利用特性去除
2.用原数组元素个数减去set集合元素个数,可以得出重复数字有几个
3.将set集合转成数组,根据上一步的重复数字个数,补足0