JAVA算法:求给定的一维数组中不重复元素的乘积

JAVA算法:求给定的一维数组中不重复元素的乘积

问题描述

给定一个一维整型数组,其中包含一些重复的元素。编写一个算法,找到数组中不重复的元素,并求出这些不重复的元素的乘积。

例如:

给定数组  {1, 6, 4, 3, 2, 2, 3, 8, 1};

其中不重复的元素为: 1, 6, 4, 3, 2, 8

这些不重复的元素的乘积为:1152。

 

算法设计

package com.bean.algorithm.beginner;

import java.util.Arrays;
import java.util.HashSet;

public class ProductOfDistinctElements {
	public static void productOfDistinct_Sorting(int[] arrA) {

		// sort the given array
		Arrays.sort(arrA);

		// all the duplicates elements are together now
		// Navigate the array and add the distinct elements,
		// skip the element if it is same as previous elements

		int current = arrA[0];
		int product = arrA[0];
		for (int i = 1; i < arrA.length; i++) {
			if (current != arrA[i]) {
				product *= arrA[i];
				current = arrA[i];
			}
		}
		System.out.println("Product of all Unique elements (Sorting Method): " + product);
	}

	public static void productOfDistinct_HashSet(int[] arrA) {

		// Create a HashSet of array elements, it will remove all the duplicates
		HashSet hashSet = new HashSet<>();
		int product = 1;
		for (int i = 0; i < arrA.length; i++) {
			if (!hashSet.contains(arrA[i])) {
				product *= arrA[i];
				hashSet.add(arrA[i]);
			}
		}
		System.out.println("Product of all Unique elements (HashSet Method: " + product);
	}

	public static void main(String[] args) {
		int[] arrA = { 1, 6, 4, 3, 2, 2, 3, 8, 1 };
		productOfDistinct_Sorting(arrA);
		productOfDistinct_HashSet(arrA);
	}
}

运行结果:

Product of all Unique elements (Sorting Method): 1152
Product of all Unique elements (HashSet Method: 1152

 

你可能感兴趣的:(算法分析与设计)