给定的队列按起始值排序
2018-11-04 本文已影响0人
heheworld
问题,给定一个无序队列,【value1,value2,value3,value4,value5】
value 数据结构如下:
class Arrayentity {
int start;
int end;
public Arrayentity() {
}
public Arrayentity(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public String toString() {
return "[start:" + start + " end:" + end + "]";
}
}
给定队列如下:
public void initData() {
Arrayentity a1 = new Arrayentity(1, 4);
Arrayentity a2 = new Arrayentity(2, 6);
Arrayentity a3 = new Arrayentity(7, 12);
Arrayentity a4 = new Arrayentity(14, 19);
Arrayentity a5 = new Arrayentity(22, 40);
arrayentityList.add(a1);
arrayentityList.add(a2);
arrayentityList.add(a3);
arrayentityList.add(a4);
arrayentityList.add(a5);
}
要求输出为:
[start:1 end:6]
[start:7 end:12]
[start:14 end:19]
[start:22 end:40]
我是这么写的
public void sort() {
List<Arrayentity> newlist = new ArrayList<>();
boolean needskip = false;
List<Arrayentity> resultlist = new ArrayList<>();
for (int i = 0; i < arrayentityList.size(); i++) {
if (needskip) {
needskip = false;
continue;
}
Arrayentity arrayentity = new Arrayentity();
resultlist.add(arrayentityList.get(i));
for (int j = i + 1; j < arrayentityList.size(); j++) {
if (arrayentityList.get(i).end >= arrayentityList.get(j).start) {
resultlist.remove(arrayentityList.get(i));
arrayentity.start = arrayentityList.get(i).start;
arrayentity.end = arrayentityList.get(j).end;
needskip = true;
}
}
if (arrayentity.start != 0 && arrayentity.end != 0) {
resultlist.add(arrayentity);
}
}
for (Arrayentity arrayentity : resultlist) {
Log.e(TAG, "result " + arrayentity.toString());
}
}