算法题解:统计一维整型数组中不重复的数组元素个数(JAVA代码)—水题
题目是给定一个一维整型数组,要求统计这个数组中不重复的数组元素的个数。
这个题目其实是一个“水题”。使用HashSet类即可解决。
在JAVA中,集(Set)的特性是集中的元素是唯一的,即不重复;无序性,即不考虑元素的顺序。
那么只需要将数组元素装入集中,输出集中元素的个数即可。
算法设计(使用HashSet)
package com.bean.algorithm.arrays;
import java.util.HashSet;
public class CountDistinctElementsInArray {
public static int countDistinct(int arr[], int n) {
HashSet<Integer> hs = new HashSet<Integer>();
for (int i = 0; i < n; i++) {
// add all the elements to the HashSet
hs.add(arr[i]);
}
// return the size of hashset as
// it consists of all Unique elements
return hs.size();
}
public static void main(String[] args) {
int arr[] = new int[] { 6, 10, 5, 4, 9, 120, 4, 6, 10 };
System.out.println(countDistinct(arr, arr.length));
}
}
程序运行结果ÿ