-
Notifications
You must be signed in to change notification settings - Fork 7
/
Program.cs
43 lines (41 loc) · 1.43 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//创建字典记录每个数字出现的次数。遍历字典,如果当前数字加一也在字典中,则有他们组成的子数组长度为两个数在字典中值的和。
//无需考虑两个数字的位置,肯定有一个会在另一个之前出现。
using System;
using System.Linq;
using System.Collections.Generic;
namespace LongestHarmoniousSubsequence
{
class Program
{
static void Main(string[] args)
{
int[] nums = { 1, 3, 2, 2, 5, 2, 3, 7 };
Console.WriteLine(FindLHS(nums));
}
static int FindLHS(int[] nums)
{
var numFrequency = new Dictionary<int, int>();
foreach (var num in nums)
{
if (!numFrequency.ContainsKey(num))
numFrequency[num] = 1;
else
numFrequency[num]++;
}
int res = 0;
foreach (var kv in numFrequency)
{
int tem = 0;
if (numFrequency.ContainsKey(kv.Key + 1))
tem = kv.Value + numFrequency[kv.Key + 1];
res = Math.Max(res, tem);
}
return res;
}
public int FindLHS_Linq(int[] nums)
{
var dict = nums.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());
return nums.Max(x => dict.ContainsKey(x + 1) ? dict[x] + dict[x + 1] : 0);
}
}
}