日期:2014-05-20  浏览次数:20594 次

一道java算法题目,请赐教.
有一组数字,要求对这组数字进行分组,规则:找出这组数字中连续的数字,作为一组,如果是单独的数字就单独作为单独的一组.最终将这组数据分成多个组.要求写出通用算法。
举例说明:如1,2,3,7,9,10,11,12,15这组数字,共有4组(第一组:1,2,3为连续的数字.第二组:7为一个独立的数字,第三组:10,11,12为连续的数字.第四组15为一个独立的数字).

------解决方案--------------------
import java.util.*;
public class Test {
public static void main(String[] args) {
int[]data = {1,2,3,7,9,10,11,12,15,16};
ArrayList/* <ArrayList <Integer> > */ list = new ArrayList/* <ArrayList <Integer> > */();
ArrayList/* <Integer> */ group;
for(int i=0; i <data.length; i++){
group = new ArrayList/* <Integer> */();
group.add(data[i]);
while(i+1 <data.length && data[i+1]==data[i]+1){
group.add(data[++i]);
}
list.add(group);
}

System.out.println(list);
}
}
------解决方案--------------------
import java.util.*;
public class Cbase {
public static void main(String[] arg) {
int a[]={1,2,3,7,9,10,11,12,15};
HashSet all=new HashSet(), group=new HashSet();
all.add(group);
boolean newflag=false;
for(int i=0; i <a.length; i++) {
if(newflag) {
group=new HashSet();
all.add(group);
newflag=false;
}
group.add(a[i]);
if(i <a.length-1 && a[i+1]-a[i]!=1) newflag=true;
}
Iterator itAll=all.iterator();
while(itAll.hasNext()) {
group=(HashSet)itAll.next();
Iterator itG=group.iterator();
while(itG.hasNext()) {
System.out.print(itG.next()+ " ");
}
System.out.println();
}
}
}