问题:给一个整数数组, 找到其中包含最多连续数的子集,比如给:15, 7, 12, 6, 14, 13, 9, 11,则返回: 5:[11, 12, 13, 14, 15]。
import java.util.HashMap;
/**
* 给一个整数数组, 找到其中包含最多连续数的子集, 比如给:15, 7, 12, 6, 14, 13, 9, 11, 则返回: 5:[11, 12,
* 13,14, 15]
*
*/
public class Main {
int[] array; // 存储数字
int[] boss; // array中每个位置上的数字的Boss的位置,同一Boss的各个数字,表明他们在同一个连续数的子集中
int[] heeler; // array中每个位置上的数字拥有的手下的数量
HashMap<Integer, Integer> map; // key为array中各个位置上对应的数字,value为该数字在数组中的位置
public Main(int[] array) {
this.array = array;
boss = new int[array.length];
// 初始化各个位置上的数字的Boss为自己
for (int i = 0; i < array.length; i++) {
boss[i] = i;
}
heeler = new int[array.length];
// 初始化每个节点上的数字的手下只有一个,即自己
for (int i = 0; i < array.length; i++) {
heeler[i] = 1;
}
// 利用HashMap来存储数字以及所在位置这种关系的目的是
// 能快速找到任何一个数字的兄弟数字所在的数字
map = new HashMap<Integer, Integer>();
for (int i = 0; i < array.length; i++) {
map.put(array[i], i);
}
}
// 找到数组中某个位置的最大Boss的位置
int findBoss(int x) {
// 如果某个位置上的数字的Boss就是自己,则表明他就是Boss
// 否则 ,必须找到他的直属Boss的Boss,并更最大的boss为自己的直属boss
if (x != boss[x])
boss[x] = findBoss(boss[x]);
return boss[x];
}
// 合并队伍:
// 规则:当位置x的boss拥有的heeler,比位置y的boss拥有的heeler少时,
// 则将位置x的boss下的所有heeler归并到位置y的boss下
// 因此位置y的boss拥有的heeler数量为原有的数量,加上位置x上的boss拥有的heeler数量
// 反之类似
public void union(int x, int y) {
int bossOfx = findBoss(x); // 找出位置x的最大boss
int bossOfy = findBoss(y);
int numHeeler_bossOfx = heeler[bossOfx]; // 找出位置x的最大boss下的heeler数量
int numHeeler_bossOfy = heeler[bossOfy];
// 当位置x与位置y的boss相同时,表明他们本来就是同一团队,不需要合并
if (bossOfx == bossOfy)
return;
if (numHeeler_bossOfx >= numHeeler_bossOfy) {
boss[bossOfy] = bossOfx;
heeler[bossOfx] += heeler[bossOfy];
}
if (numHeeler_bossOfx < numHeeler_bossOfy) {
boss[bossOfx] = bossOfy;
heeler[bossOfy] += heeler[bossOfx];
}
}
// 求最大子集
public void getMax() {
for (int i = 0; i < array.length; i++) {
int leftBrother = array[i] - 1;
//如果位置i的数字存在比自己小于1的数字,则进行合并
if (map.containsKey(leftBrother)) {
int place = map.get(leftBrother);
union(place, i);
}
int rightBrother = array[i] + 1;
//如果位置i的数字存在比自己大于1的数字,则进行合并
if (map.containsKey(rightBrother)) {
int place = map.get(rightBrother);
union(i, place);
}
}
int max = 0; // 最大子集个数
int bo = 0; // 最大子集的boss
for (int i = 0; i < array.length; i++) {
if (heeler[i] > max) {
max = heeler[i];
bo = i;
}
}
System.out.println("最大子集个数为: " + max);
for (int i = 0; i < array.length; i++) {
if (boss[i] == bo) {
System.out.print(array[i] + " ");
}
}
}
public static void main(String[] args) {
int[] arr = new int[] { 15, 7, 12, 6, 14, 13, 9, 11 };
Main test = new Main(arr);
test.getMax();
}
}