594. Longest Harmonious Subsequence

2018/04/14 leetcode 共 717 字,约 3 分钟

Title

the problem link

We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.

Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.

Example 1:
Input: [1,3,2,2,5,2,3,7]
Output: 5

Explanation: The longest harmonious subsequence is [3,2,2,2,3].

Note: The length of the input array will not exceed 20,000.

题目大意:求一个数组里相差为1的元素组成的数组的元素个数,一定要有相差为1的

Solution

//cpp:
class Solution {
public:
	int findLHS(vector<int>& nums) {
		unordered_map<int, int> map1;
		for (int i = 0; i < nums.size(); i++) {
			map1[nums[i]]++;
		}
		int ans = 0;
		for (int i = 0; i < nums.size(); i++) {
			ans = max(ans, map1[nums[i]+1]>0?map1[nums[i]] + map1[nums[i] + 1]:0);

		}
		return ans;
	}
};

Search

    Table of Contents