[英]Make data structure for stock of boxes
我如何為箱子庫存制作數據結構,以便我可以盡可能高效地實現以下方法?
所有的盒子都有一個方形底(長=寬),但它們不一定是立方體(高不一定等於長=寬)。
功能是
INSERTBOX(side, height) (side=length=width) - 在數據結構中插入一個新框
REMOVEBOX(side, height) - 從庫存中刪除一個盒子
GETBOX( side , height ) - 返回一個體積最小的盒子,它的長度至少是邊,高度至少是高度
CHECKBOX( side , height ) - 檢查數據結構中是否存在長度至少為邊且高度至少為高度的框
我認為實現這一點的方法是通過帶有卷鍵的 RB 樹,但是如果我找到具有所需體積的框,我不知道如何在這些潛在框(最小體積的子樹)中找到具有滿足要求的最小尺寸。
任何提示? 這是正確的方法嗎? 或者我應該考慮其他數據結構?
我不認為這個問題需要復雜的數據結構
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Box {
private int side;
private int height;
private int volume;
public Box(final int side, final int height) {
this.side = side;
this.height = height;
this.volume = side * height;
}
public static String getKey(final int side, final int height) {
return side + "_" + height;
}
public int getSide() {
return side;
}
public int getHeight() {
return height;
}
public int getVolume() {
return height;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Box box = (Box) o;
return side == box.side &&
height == box.height;
}
@Override
public int hashCode() {
return Objects.hash(side, height);
}
}
public class StockOfBoxes {
private Map<String, Box> dictionary = new HashMap<>();
public void insert(int side, int height) {
dictionary.put(Box.getKey(side, height), new Box(side, height));
}
public void remove(int side, int height) {
dictionary.remove(Box.getKey(side, height));
}
public Box get(int side, int height) {
List<Box> filtered = dictionary
.values()
.stream()
.filter(b -> b.getHeight() >= height && b.getSide() >= side)
.collect(Collectors.toList());
Box boxWithMinVolume = null;
for (Box box: filtered) {
if (boxWithMinVolume == null || boxWithMinVolume.getVolume() > box.getVolume()) {
boxWithMinVolume = box;
}
}
return boxWithMinVolume;
}
public boolean check(int side, int height) {
return dictionary
.values()
.stream()
.anyMatch(b -> b.getHeight() >= height && b.getSide() >= side);
}
}
方法的時間復雜度:
插入 - O(1)
刪除 - O(1)(見這個)
進行)
檢查)
我認為任何數據結構都不會讓您改善這個數字。 即使您以某種方式改進了獲取/檢查,它也會導致插入的時間復雜度變差。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.