题解 | #数组中的最长连续子序列#
数组中的最长连续子序列
http://www.nowcoder.com/practice/eac1c953170243338f941959146ac4bf
一开始并没有想起来先用排序做,直接用的HashMap,解法比较通俗易懂
思路是遍历整个数组,当前值继承上一个连续的数+1,如果没找到上一个连续的值就设置为1
然后对下一个连续的值进行处理,如果之前保存的map中有下一个连续的值,则遍历每一个连续的值并且+1
最后输出map中最大的一个值
import java.util.*;
public class Solution {
/**
* max increasing subsequence
* @param arr int整型一维数组 the array
* @return int整型
*/
public int MLS (int[] arr) {
Map<Integer,Integer> map = new HashMap();
int max = 0;
for(int i = 0; i<arr.length; i++){
int count = map.getOrDefault(arr[i]-1,0)+1;
map.put(arr[i],count);
int upper = arr[i]+1;
while(map.containsKey(upper)){
map.put(upper,++count);
upper++;
}
}
for(int i:map.keySet()){
max = Math.max(max,map.get(i));
}
return max;
}
}
查看9道真题和解析
