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];
}
}