算法题解:统计一维整型数组中不重复的数组元素个数(JAVA代码)—水题

算法题解:统计一维整型数组中不重复的数组元素个数(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));
	}

}

程序运行结果ÿ

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值