Skip to content

Commit

Permalink
Add solution and test-cases for problem 594
Browse files Browse the repository at this point in the history
  • Loading branch information
0xff-dev committed Apr 16, 2024
1 parent 09a1dcb commit 8987924
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 22 deletions.
31 changes: 18 additions & 13 deletions leetcode/501-600/0594.Longest-Harmonious-Subsequence/README.md
Original file line number Diff line number Diff line change
@@ -1,28 +1,33 @@
# [594.Longest Harmonious Subsequence][title]

> [!WARNING|style:flat]
> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm)
## Description
We define a harmonious array as an array where the difference between its maximum value and its minimum value is **exactly** `1`.

Given an integer array `nums`, return the length of its longest harmonious subsequence among all its possible subsequences.

A **subsequence** of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.

**Example 1:**

```
Input: a = "11", b = "1"
Output: "100"
Input: nums = [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].
```

## 题意
> ...
## 题解
**Example 2:**

### 思路1
> ...
Longest Harmonious Subsequence
```go
```
Input: nums = [1,2,3,4]
Output: 2
```

**Example 3:**

```
Input: nums = [1,1,1,1]
Output: 0
```

## 结语

Expand Down
21 changes: 19 additions & 2 deletions leetcode/501-600/0594.Longest-Harmonious-Subsequence/Solution.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
package Solution

func Solution(x bool) bool {
return x
import "sort"

func Solution(nums []int) int {
keys := make(map[int]int)
a := make([]int, 0)
for _, n := range nums {
if _, ok := keys[n]; !ok {
a = append(a, n)
}
keys[n]++
}
sort.Ints(a)
ans := 0
for i := 1; i < len(a); i++ {
if a[i]-a[i-1] == 1 && keys[a[i]]+keys[a[i-1]] > ans {
ans = keys[a[i]] + keys[a[i-1]]
}
}
return ans
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ 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, 2, 2, 5, 2, 3, 7}, 5},
{"TestCase2", []int{1, 2, 3, 4}, 2},
{"TestCase3", []int{1, 1, 1, 1}, 0},
}

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

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

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

0 comments on commit 8987924

Please sign in to comment.