Skip to content

Commit

Permalink
Merge pull request #906 from 0xff-dev/2799
Browse files Browse the repository at this point in the history
Add solution and test-cases for problem 2799
  • Loading branch information
6boris committed Jun 14, 2024
2 parents 4316b8a + f47e2c6 commit 1e6c4e5
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 9 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# [2799.Count Complete Subarrays in an Array][title]

## Description
You are given an array `nums` consisting of **positive** integers.

We call a subarray of an array **complete** if the following condition is satisfied:

- The number of **distinct** elements in the subarray is equal to the number of distinct elements in the whole array.

Return the number of **complete** subarrays.

A **subarray** is a contiguous non-empty part of an array.

**Example 1:**

```
Input: nums = [1,3,1,2,2]
Output: 4
Explanation: The complete subarrays are the following: [1,3,1,2], [1,3,1,2,2], [3,1,2] and [3,1,2,2].
```

**Example 2:**

```
Input: nums = [5,5,5,5]
Output: 10
Explanation: The array consists only of the integer 5, so any subarray is complete. The number of subarrays that we can choose is 10.
```

## 结语

如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-golang-algorithm][me]

[title]: https://leetcode.com/problems/count-complete-subarrays-in-an-array
[me]: https://github.com/kylesliu/awesome-golang-algorithm
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
package Solution

func Solution(x bool) bool {
return x
func Solution(nums []int) int {
in := make(map[int]struct{})
for _, n := range nums {
in[n] = struct{}{}
}
distinct := len(in)
ans := 0
for i := 0; i < len(nums); i++ {
ti := map[int]struct{}{nums[i]: {}}
if len(ti) == distinct {
ans++
}
for pre := i - 1; pre >= 0; pre-- {
ti[nums[pre]] = struct{}{}
if len(ti) == distinct {
ans++
}
}
}
return ans
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,11 @@ func TestSolution(t *testing.T) {
// 测试用例
cases := []struct {
name string
inputs bool
expect bool
inputs []int
expect int
}{
{"TestCase", true, true},
{"TestCase", true, true},
{"TestCase", false, false},
{"TestCase1", []int{1, 3, 1, 2, 2}, 4},
{"TestCase2", []int{5, 5, 5, 5}, 10},
}

// 开始测试
Expand All @@ -30,10 +29,10 @@ func TestSolution(t *testing.T) {
}
}

// 压力测试
// 压力测试
func BenchmarkSolution(b *testing.B) {
}

// 使用案列
// 使用案列
func ExampleSolution() {
}

0 comments on commit 1e6c4e5

Please sign in to comment.