内存资源分配
标题:内存资源分配 | 时间限制:1秒 | 内存限制:32768K | 语言限制:不限
有一个简易内存池,内存按照大小粒度分类,每个粒度有若干个可用内存资源,用户会进行一系列内存申请,需要按需分配内存池中的资源,返回申请结果成功失败列表。分配规则如下:
1、分配的内存要大于等于内存申请量,存在满足需求的内存就必须分配,优先分配粒度小的,但内存不能拆分使用。
2、需要按申请顺序分配,先申请的先分配。
3、有可用内存分配则申请结果为true,没有可用内存分配则返回false。
注:不考虑内存释放。
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String resourceStr = scanner.next();
String applyStr = scanner.next();
try {
//资源信息
List<Integer> resourceList = new ArrayList<>();
String[] typeResStrArray = resourceStr.split(",");
for (String typeResStr : typeResStrArray) {
String[] resInfo = typeResStr.split(":");
int resSize = Integer.parseInt(resInfo[0]);
for (int i = 0; i < Integer.parseInt(resInfo[1]); ++i) {
resourceList.add(resSize);
}
}
//资源申请情况
List<Integer> applyList = new ArrayList<>();
String[] applyStrArray = applyStr.split(",");
for (String apply : applyStrArray) {
applyList.add(Integer.parseInt(apply));
}
//输出结果
for (int i = 0; i < applyList.size(); ++i) {
int apply = applyList.get(i);
boolean result = false;
for (int resource : resourceList) {
if (apply <= resource) {
result = true;
resourceList.remove(resourceList.indexOf(resource));
break;
}
}
System.out.print(result);
if (i != applyList.size() - 1) {
System.out.print(",");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String inString1 = scanner.nextLine().trim();
String inString2 = scanner.nextLine().trim();
TreeMap<Integer, Integer> createBuffer = new TreeMap<>();
String[] strings = inString1.split(",");
//遍历内存池信息
for (String string : strings) {
String[] buffers = string.split(":");
createBuffer.put(Integer.parseInt(buffers[0]), Integer.parseInt(buffers[1]));
}
String[] consumeLine = inString2.split(",");
if (consumeLine==null || consumeLine.length==0){
System.out.println();
continue;
}
StringBuffer result = new StringBuffer();
for (String consume : consumeLine) {
if (consume == null || "".equals(consume)){
continue;
}
int consumeInt = Integer.parseInt(consume);
boolean flag = isExistTheMemory(createBuffer, consumeInt);
result.append(flag + ",");
}
result.deleteCharAt(result.length() - 1);
System.out.println(result.toString());
}
}
private static boolean isExistTheMemory(TreeMap<Integer, Integer> createBuffer, int consumeInt) {
for (Integer bufferSizeKey : createBuffer.keySet()){
if (bufferSizeKey >= consumeInt && createBuffer.get(bufferSizeKey)>0){
createBuffer.put(bufferSizeKey,createBuffer.get(bufferSizeKey)-1);
return true;
}
}
return false;
}
}// manfen
深信服公司福利 832人发布