思路:
使用双指针的方法
class Solution {
public:
int findLHS(vector<int>& nums) {
//双指针
//先排序好数组
sort(nums.begin(),nums.end());
int ret=0;//记载最长子数列的个数
int begin=0;//从nums 0 开始
for(int end=1;end<nums.size();end++)
{
if((nums[end]-nums[begin])>1)
{
begin++;//起始位置前进一步
}
if((nums[end]-nums[begin])==1)
{
//更新子序列长度
ret=ret > end-begin+1 ? ret : end-begin+1;
}
}
return ret;
}
};
如有错误,多多指教!