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];
			}
		}
		
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值