每日OJ_牛客_NC95数组中的最长连续子序列_排序+模拟_C++_Java
目录
牛客_NC95数组中的最长连续子序列_排序和模拟
题目解析
C++代码
Java代码
牛客_NC95数组中的最长连续子序列_排序+模拟
数组中的最长连续子序列_牛客题霸_牛客网
题目解析
排序 + 模拟。但是要注意处理数字相同的情况,还要注意去重。
排序后使用一个变量count来记录当前有序序列的长度。
- 如果当前元素比前一个大1,说明他们可以构成连续的序列,count就加1。
- 如果相等就跳过。
- 否则就不能构成连续的序列,count要重置为1,要重新统计。
C++代码
class Solution
{
public:int MLS(vector<int>& arr){sort(arr.begin(), arr.end());int n = arr.size(), ret = 0;for(int i = 0; i < n; ){int j = i + 1, count = 1;while(j < n){if(arr[j] - arr[j - 1] == 1){count++;j++;}else if(arr[j] - arr[j - 1] == 0){j++;}else{break;}}ret = max(ret, count);i = j;}return ret;}
};
Java代码
import java.util.*;
public class Solution
{public int MLS (int[] arr){Arrays.sort(arr);int n = arr.length, ret = 0;for(int i = 0; i < n; ){int j = i + 1, count = 1;while(j < n){if(arr[j] - arr[j - 1] == 1){count++;j++;}else if(arr[j] - arr[j - 1] == 0){j++;}else{break;}}ret = Math.max(ret, count);i = j;}return ret;}
}