首页 > 解决方案 > 为什么我的算法不检查链表的最后一个元素?

问题描述

我做了一个小系统,它需要一个座位数来填充一个电影院,里面有一定数量的座位(没有排)。现在我做了一个方法来填充座位并返回一个地图,地图返回在什么位置有一定数量的座位是空闲的(例如 3-2 表示从位置 3 开始有两个座位彼此相邻。

这工作得很好,但是如果我说最多有 5 个座位​​,而座位 5 是空闲的,则该方法不会将其返回到地图。

这是使用的代码:

对象座位

public class Seat {
    public Integer availability;
    public Integer seatNumber;

    public boolean IsFree() {
        if(availability == 0){
            return true;
        }
        else return false;
    }

    public String toString() {
        return "{ " + seatNumber + ", free: " + IsFree() + " } ";
    }
}

此方法创建一个 LinkedList 并通过 giveRandomAvailability() 方法用“1”(已采用)或“0”(可用)填充可用性

static LinkedList fillList(int seats){

    LinkedList<Seat> list = new LinkedList<Seat>();
    seats = seatCount;

    for(int i = 0; i < seats; i++){
        Seat seat = new Seat();
        seat.availability = giveRandomAvailability();
        seat.seatNumber = (i + 1);
        list.add(seat);
    }

    return list;
}

这是无法正常工作的方法,它应该用可用座位填充地图,但是当最后一个元素可用时,它不会映射。这是一个示例输出:

[{ 1, free: true } , { 2, free: true } , { 3, free: false } , { 4, free: true } , { 5, free: true } ]
{1=2}

您可以看到第一部分处理得很好,但它也应该包含 4 = 2。

方法:

static Map fillSeats(){
    int n = 3;
    LinkedList<Seat> newList = fillList(seatCount);
    int consecutiveLength = 0; // Consecutive free seats length
    int index = 0;
    int startIndex = -1; // Store the start of consecutive free seats
    System.out.println(newList.toString());
    Map<Integer, Integer> consecutiveMap = new HashMap<>(); // Store startIndex -> length

    for (Seat seat : newList) {
        if (seat.IsFree()) {
            if (startIndex < 0) {
                startIndex = index;
            }
            consecutiveLength ++;
        } else {
            consecutiveMap.put(startIndex + 1, consecutiveLength);
            if (consecutiveLength == n) {
                // Found, do something here
            }
            // Reset
            startIndex = -1;
            consecutiveLength = 0;
        }
        index++;
    }
    return consecutiveMap;
}

我在这里找不到问题,将不胜感激。

标签: javaalgorithmlinked-list

解决方案


好吧,如果最后一组连续座位包含List. 您应该在循环之后添加逻辑以添加最后一组:

for (Seat seat : newList) {
    if (seat.IsFree()) {
        if (startIndex < 0) {
            startIndex = index;
        }
        consecutiveLength ++;
    } else {
        consecutiveMap.put(startIndex + 1, consecutiveLength);
        if (consecutiveLength == n) {
            // Found, do something here
        }
        // Reset
        startIndex = -1;
        consecutiveLength = 0;
    }
    index++;
}
// added logic:
if (startIndex >= 0) {
    consecutiveMap.put(startIndex + 1, consecutiveLength);
}
return consecutiveMap;

推荐阅读