|
| 1 | +# [1852. Distinct Numbers in Each Subarray](https://leetcode.com/problems/distinct-numbers-in-each-subarray) |
| 2 | + |
| 3 | +[中文文档](/solution/1800-1899/1852.Distinct%20Numbers%20in%20Each%20Subarray/README.md) |
| 4 | + |
| 5 | +## Description |
| 6 | + |
| 7 | +<p>Given an integer array <code>nums</code> and an integer <code>k</code>, you are asked to construct the array <code>ans</code> of size <code>n-k+1</code> where <code>ans[i]</code> is the number of <strong>distinct</strong> numbers in the subarray <code>nums[i:i+k-1] = [nums[i], nums[i+1], ..., nums[i+k-1]]</code>.</p> |
| 8 | + |
| 9 | + |
| 10 | + |
| 11 | +<p>Return <em>the array </em><code>ans</code>.</p> |
| 12 | + |
| 13 | + |
| 14 | + |
| 15 | +<p> </p> |
| 16 | + |
| 17 | +<p><strong>Example 1:</strong></p> |
| 18 | + |
| 19 | + |
| 20 | + |
| 21 | +<pre> |
| 22 | + |
| 23 | +<strong>Input:</strong> nums = [1,2,3,2,2,1,3], k = 3 |
| 24 | + |
| 25 | +<strong>Output:</strong> [3,2,2,2,3] |
| 26 | + |
| 27 | +<strong>Explanation: </strong>The number of distinct elements in each subarray goes as follows: |
| 28 | + |
| 29 | +- nums[0:2] = [1,2,3] so ans[0] = 3 |
| 30 | + |
| 31 | +- nums[1:3] = [2,3,2] so ans[1] = 2 |
| 32 | + |
| 33 | +- nums[2:4] = [3,2,2] so ans[2] = 2 |
| 34 | + |
| 35 | +- nums[3:5] = [2,2,1] so ans[3] = 2 |
| 36 | + |
| 37 | +- nums[4:6] = [2,1,3] so ans[4] = 3 |
| 38 | + |
| 39 | +</pre> |
| 40 | + |
| 41 | + |
| 42 | + |
| 43 | +<p><strong>Example 2:</strong></p> |
| 44 | + |
| 45 | + |
| 46 | + |
| 47 | +<pre> |
| 48 | + |
| 49 | +<strong>Input:</strong> nums = [1,1,1,1,2,3,4], k = 4 |
| 50 | + |
| 51 | +<strong>Output:</strong> [1,2,3,4] |
| 52 | + |
| 53 | +<strong>Explanation: </strong>The number of distinct elements in each subarray goes as follows: |
| 54 | + |
| 55 | +- nums[0:3] = [1,1,1,1] so ans[0] = 1 |
| 56 | + |
| 57 | +- nums[1:4] = [1,1,1,2] so ans[1] = 2 |
| 58 | + |
| 59 | +- nums[2:5] = [1,1,2,3] so ans[2] = 3 |
| 60 | + |
| 61 | +- nums[3:6] = [1,2,3,4] so ans[3] = 4 |
| 62 | + |
| 63 | +</pre> |
| 64 | + |
| 65 | + |
| 66 | + |
| 67 | +<p> </p> |
| 68 | + |
| 69 | +<p><strong>Constraints:</strong></p> |
| 70 | + |
| 71 | + |
| 72 | + |
| 73 | +<ul> |
| 74 | + <li><code>1 <= k <= nums.length <= 10<sup>5</sup></code></li> |
| 75 | + <li><code>1 <= nums[i] <= 10<sup>5</sup></code></li> |
| 76 | +</ul> |
| 77 | + |
| 78 | +## Solutions |
| 79 | + |
| 80 | +<!-- tabs:start --> |
| 81 | + |
| 82 | +### **Python3** |
| 83 | + |
| 84 | +```python |
| 85 | + |
| 86 | +``` |
| 87 | + |
| 88 | +### **Java** |
| 89 | + |
| 90 | +```java |
| 91 | + |
| 92 | +``` |
| 93 | + |
| 94 | +### **...** |
| 95 | + |
| 96 | +``` |
| 97 | +
|
| 98 | +``` |
| 99 | + |
| 100 | +<!-- tabs:end --> |
0 commit comments