1、题目描述
https://blog.51cto.com/u_15127575/3271270
2、代码:
import java.util.*; // 样例2: // 5 // REQUEST=10 // REQUEST=20 // RELEASE=0 // REQUEST=20 // REQUEST=10 // 输出样例2: // 0 // 10 // 30 // 0 public class 内存分配_self { // key存内存开始地址,value存内存的结束地址 public static TreeMap<Integer, Integer> treeMap = new TreeMap<>(); public static int defaulttart = 0; public static int defaultEnd = 100; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int line = Integer.parseInt(scanner.nextLine()); for (int i = 0; i < line; i++) { String command = scanner.nextLine(); if (command.startsWith("REQUEST=")) { String s = command.split("=")[1]; int size = Integer.parseInt(s); System.out.println(request(size)); System.out.println(treeMap.toString()); } else { String s = command.split("=")[1]; int startAddress = Integer.parseInt(s); release(startAddress); System.out.println(treeMap.toString()); } } } // 返回分配到的内存首地址 // 0-9 20-39 50-69 public static String request(int size) { if (size < 0 || size > 100) { System.out.println("erro"); } if (treeMap.isEmpty()) { treeMap.put(defaulttart, defaulttart + size - 1); return String.valueOf(defaulttart); } int curStart = defaulttart; ArrayList<Integer> begains = new ArrayList<>(treeMap.keySet()); // 判断已使用的内存中间是否有空闲的内存 for (int i = 0; i < begains.size(); i++) { if (begains.get(i) - curStart >= size) { treeMap.put(curStart, curStart + size-1); return String.valueOf(curStart); } else { curStart = treeMap.get(begains.get(i)) + 1; } } // 最大内存和已使用的内存地址的最大值是否空闲 if (defaultEnd - curStart >= size) { treeMap.put(curStart,curStart+size-1); return String.valueOf(curStart); } else { return "erro"; } } // 释放内存 public static void release(int startAddress) { if (treeMap.containsKey(startAddress)) { treeMap.remove(startAddress); } else { System.out.println("erro"); } } }
。。