// 简易内存池
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();sc.nextLine();
List<int[]> arrayList =new ArrayList<>();
arrayList.add(new int[]{0,100,0});//0:首地址, 100:尾地址, 0|1(空闲|使用中)
for (int j = 0; j < num; j++) {
String[] str = sc.nextLine().split("=");
int flag =0;
if (str[0].equals("REQUEST")){
for (int i = 0; i < arrayList.size(); i++) {
int start = arrayList.get(i)[0],
end = arrayList.get(i)[1],
free = arrayList.get(i)[2];
int d = Integer.parseInt(str[1]);
if (d <= (end - start)&&free==0){
arrayList.remove(i);
arrayList.add(new int[]{start,start+d,1});
arrayList.add(new int[]{start+d,end,0});
//添加完后排序
arrayList.sort(Comparator.comparingInt(arr->arr[0]));
System.out.println(start);
flag=1;
break;
}
}
if (flag==0){
System.out.println("error");
}
}
else {
for (int i = 0; i < arrayList.size(); i++) {
int start = arrayList.get(i)[0],
end = arrayList.get(i)[1],
free = arrayList.get(i)[2];;
int d = Integer.parseInt(str[1]);
if (d == start&&free==1){
// 判断左右有没有空闲内存
int left = 0,right=0;
int[] removeleft =new int[3],removeright = new int[3];
// 第一个没有右空闲内存
if (i!=0&&arrayList.get(i-1)[2]==0){
removeleft = arrayList.remove(i - 1);
left=1;
}
// 最后一个没有左空闲内存
if (i!=arrayList.size()-1&&arrayList.get(i+1)[2]==0){
removeright = arrayList.remove(i + 1);
right=1;
}
arrayList.remove(i);
if (left==1&&right==1){
arrayList.add(new int[]{removeleft[0],removeright[1],0});
} else if (left==1&&right==0) {
arrayList.add(new int[]{removeleft[0],end,0});
} else if (left==0&&right==1) {
arrayList.add(new int[]{start,removeright[1],0});
}else {
arrayList.add(new int[]{start,end,0});
}
//添加完后排序
arrayList.sort(Comparator.comparingInt(arr->arr[0]));
flag=1;
break;
}
}
if (flag==0){
System.out.println("error");
}
}
}
}
华为OD机考题目:简易内存池
最新推荐文章于 2026-01-01 15:39:09 发布
6214

被折叠的 条评论
为什么被折叠?



