输入10个整数,显示去除重复数后的结果。
【样例输出】
Enter n:
Enter n numbers:
The number of distinct values is 6
3 2 4 5 6 12
你应该先自己写代码来实现,如果代码中遇到问题,可以到这里来咨询。
如果直接就拿题目来问,就对学习太不负责任了。失去了锻炼的机会。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter n:");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter " + n + " numbers:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < n; i++) {
set.add(arr[i]);
}
System.out.println("The number of distinct values is " + set.size());
System.out.print("Distinct values are: ");
for (Integer num : set) {
System.out.print(num + " ");
}
}
}
希望采纳,谢谢
下边有6种去重方法,有帮助的话,采纳下
// HashSet去重
HashSet<Integer> set = new HashSet<>(list);
System.out.println("去重后:" + set);
// TreeSet去重
TreeSet<Integer> set = new TreeSet<>(list);
System.out.println("去重后:" + set);
// LinkedHashSet 去重
LinkedHashSet<Integer> set = new LinkedHashSet<>(list);
System.out.println("去重后:" + set);
// Stream distinct去重
list = list.stream().distinct().collect(Collectors.toList());
System.out.println("去重后:" + list);
// 迭代器去重
public static void method(List<Integer> list) {
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
// 获取循环的值
Integer item = iterator.next();
// 如果存在两个相同的值
if (list.indexOf(item) != list.lastIndexOf(item)) {
// 移除最后相同的值
iterator.remove();
}
}
System.out.println("去重后:" + list);
}
// forEach遍历去重
public static void method(List<Integer> list) {
List<Integer> newList = new ArrayList<>(list.size());
list.forEach(i -> {
if (!newList.contains(i)) { // newList中不存在则添加
newList.add(i);
}
});
System.out.println("去重后:" + newList);
}
用set数据结构就可以了,没啥难度,作业自己写