public class Solution {
    public int FindLHS(int[] nums) {
        Dictionary<int, int> dic = new Dictionary<int, int>();
            foreach (var num in nums)
            {
                if (!dic.ContainsKey(num))
                {
                    dic.Add(num, 1);
                }
                else
                {
                    dic[num]++;
                }
            }

            var list = dic.OrderBy(x => x.Key).ToList();
            if (list.Count == 1)
            {
                return 0;
            }
            else
            {
                var lastkey = 0;
                var lastLen = 0;
                var max = 0;
                for (int i = 0; i < list.Count; i++)
                {
                    if (i == 0)
                    {
                        lastkey = list[i].Key;
                        lastLen = list[i].Value;
                        continue;
                    }
                    else
                    {
                        var curKey = list[i].Key;
                        var curLen = list[i].Value;
                        if (curKey - lastkey == 1)
                        {
                            var totalLen = lastLen + curLen;
                            if (max < totalLen)
                            {
                                max = totalLen;
                            }
                        }
                        lastkey = curKey;
                        lastLen = curLen;
                    }
                }
                return max;
            }
    }
}

https://leetcode.com/problems/longest-harmonious-subsequence/#/description

posted on 2017-05-22 17:32  Sempron2800+  阅读(145)  评论(0编辑  收藏  举报