# 计算具有与原始数组相同的不同元素的子数组

## 问题陈述

“计算具有与原始元素相同的不同元素的子数组 排列”表示您得到了一个整数数组。 问题陈述要求找出包含原始数组中包含的所有不同元素的子数组的总数。

## 使用案列

`arr[] = {2, 1, 3, 2, 3}`
`5`

`arr[] = {2, 4, 3, 4, 1, 2}`
`4`

## 计算具有与原始数组相同的不同元素的子数组的算法

```1. Declare a map.
2. Add all the values of array into the map with 1 as each key’s value.
3. Find the size of the map, store it to k and clear the map.
4, Set output, right, and maxsa to 0.
5. Traverse the array, from i=0, to i < n(length of the array).
1. While the right is less than n and maxsa is less than k,
1. Insert arr[right] and increase its frequency by 1.
2. Check if the map’s value of current array element (arr[right]) is equal to 1 if true then increase the count of maxsa by 1.
2. Increase the count of right by 1.
3. If maxsa is equal to k, then update output à output += (n - right + 1).
4. Insert the value of current arr[left] and decrease its frequency by 1.
5. If the map’s arr[left] is equal to 0, then decrease the value of maxsa by 1.
6. Return output.```

## 代码

### C ++代码对子数组的总数与原始数组相同的子数组进行计数

```#include<iostream>
#include<unordered_map>

using namespace std;

int getSubArrayDistinct(int arr[], int n)
{
unordered_map<int, int> MAP;
for (int i = 0; i < n; ++i)
MAP[arr[i]] = 1;

int k = MAP.size();

MAP.clear();

int output = 0, right = 0, maxsa = 0;
for (int left = 0; left < n; ++left)
{
while (right < n && maxsa < k)
{
++MAP[ arr[right] ];

if (MAP[ arr[right] ] == 1)
++maxsa;

++right;
}
if (maxsa == k)
{
output += (n - right + 1);
}
--MAP[ arr[left] ];

if (MAP[ arr[left] ] == 0)
{
--maxsa;
}
}
return output;
}
int main()
{
int arr[] = {2, 1, 3, 2, 3};
int n = sizeof(arr) / sizeof(arr[0]);
cout << getSubArrayDistinct(arr, n);
}
```
`5`

### Java代码来计算具有与原始数组相同的不同元素的子数组

```import java.util.HashMap;

class SubarrayWithDistinctEle
{
public static int getSubArrayDistinct(int arr[], int n)
{
HashMap<Integer, Integer> MAP = new HashMap<Integer,Integer>()
{
@Override
public Integer get(Object key)
{
if(!containsKey(key))
return 0;
return super.get(key);
}
};

for (int i = 0; i < n; ++i)
MAP.put(arr[i], 1);
int k = MAP.size();

MAP.clear();

int output = 0, right = 0, maxsa = 0;
for (int left = 0; left < n; ++left)
{
while (right < n && maxsa < k)
{
MAP.put(arr[right], MAP.get(arr[right]) + 1);

if (MAP.get(arr[right])== 1)
{
++maxsa;
}

++right;
}
if (maxsa == k)
{
output += (n - right + 1);
}

MAP.put(arr[left], MAP.get(arr[left]) - 1);

if (MAP.get(arr[left]) == 0)
--maxsa;
}
return output;
}
public static void main(String args[])
{
int arr[] = {2, 1, 3, 2, 3};
int n=arr.length;
System.out.println(getSubArrayDistinct(arr, n));
}
}
```
`5`