和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。
现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。
思路:
1.从S找到了不重复的子数组,按照从小到大排序S[n1, n2, …, nm];
2.从S[n1,n2,…nm]去掉部分元素,使得剩余的s[n11, n12, n21, n22, …, nm]中的任意ni1满足ni2 = ni1 + 1;
3.s[n11, n12, n21, n22, …, nm]满足:存在ni1,ni2组成的数组是和谐数组T;
public static int findLHS(int[] nums) {
if(nums == null || nums.length <= 0){
return 0;
}
if(nums.length >= 20000){
return 0;
}
Map<Integer, Integer> map = new TreeMap<Integer, Integer>();
for(int i = 0; i < nums.length; i ++){
map.put(nums[i], nums[i]);
}
//S[n1, n2, ..., nm]
List<Integer> keyList = new ArrayList<Integer>();
for(int key : map.keySet()){
keyList.add(key);
}
//s[n11, n12, n21, n22, ..., nm]-->s[n11, n21, ..., nm]
List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < keyList.size() - 1; i ++){
if(keyList.get(i + 1) == keyList.get(i) + 1){
list.add(keyList.get(i));
}
}
List<Integer> maxList = new ArrayList<Integer>(20000);
List<Integer> tempList = null;
int maxSub = 0;
int startNum = 0;
int maxLength = 0;
fora : for(int num : list){
tempList = new ArrayList<Integer>();
for(int i = 0; i < nums.length; i ++){
if(nums[i] == num || nums[i] == num + 1){
tempList.add(nums[i]);
}
}
if(tempList.size() > 1 && tempList.size() >= maxLength){
startNum = tempList.get(0);
maxSub = 0;//最大元素与最小元素的差为1,不满足不是和谐数组
for(int ii = 1; ii < tempList.size(); ii ++){
if(startNum - tempList.get(ii) != 0){
maxSub = 1;
}
}
if(maxSub == 0){//最大元素与最小元素的差为1,不满足不是和谐数组
continue fora;
}
maxList.clear();
maxList.addAll(tempList);
maxLength = tempList.size();
}
}
for(int num : maxList){
System.out.print(num + " ");
}
System.out.println();
return maxList.size();
}
输入nums = {1,3,2,2,5,2,3,7}
输出和谐数组:3 2 2 2 3
长度:5