Intuit OA 面试真题解析:RunCollection personalBest 最快总用时统计

30次阅读
没有评论

We are writing software to collect and manage data on how fast racers can complete obstacle courses.

An obstacle course is a series of difficult physical challenges (like walls, hurdles, and ponds) that a racer must go through.

Each course consists of multiple obstacles. The software stores how long it takes for racers to finish each obstacle, and provides useful statistics based on those times.

Definitions:

  • A run is a particular attempt to complete an entire obstacle course.
  • A run collection is a group of runs on a particular course by the user.
  • An obstacle is a portion of a course. We track how long it takes to finish each portion of the course.

Given the following classes, implement the missing method behavior:

class Course {
    public String title;
    public int obstacleCount;

    public Course(String courseTitle, int obstacles) {
        title = courseTitle;
        obstacleCount = obstacles;
    }

    @Override
    public boolean equals(Object o) {if (!(o instanceof Course)) {return false;}
        Course c = (Course) o;
        return c.title == this.title && c.obstacleCount == this.obstacleCount;
    }

    @Override
    public int hashCode() {return (title == null ? 0 : title.hashCode()) * obstacleCount;
    }
}

class Run {
    public Course course;
    public boolean complete;
    public List<Integer> obstacleTimes;

    public Run(Course runCourse) {
        course = runCourse;
        complete = false;
        obstacleTimes = new ArrayList<>();}

    public void addObstacleTime(int obstacleTime) {if (complete) {throw new IllegalStateException("Cannot add obstacle to complete run");
        }
        obstacleTimes.add(obstacleTime);
        if (obstacleTimes.size() == course.obstacleCount) {complete = true;}
    }

    public int getRunTime() {return obstacleTimes.stream().mapToInt(Integer::intValue).sum();}
}

class RunCollection {
    public Course course;
    public List<Run> runs;

    public RunCollection(Course collectionCourse) {
        course = collectionCourse;
        runs = new ArrayList<>();}

    public int getNumRuns() {return runs.size();
    }

    public void addRun(Run run) {if (!run.course.equals(course)) {throw new IllegalArgumentException("run's Course is not the same as the RunCollection's");
        }
        runs.add(run);
    }

    public int personalBest() {return runs.stream().mapToInt(v -> v.getRunTime()).min().orElse(Integer.MAX_VALUE);
    }
}

Implement the code so that the provided tests pass.

这道题考察的是 Java 对象建模与集合统计:需要维护 Course、Run 和 RunCollection 三个类之间的关系,Run 负责按障碍物顺序累加每一段用时,并在达到 course.obstacleCount 后标记完成;RunCollection 负责校验跑步记录是否属于同一条赛道,并计算个人最好成绩 personalBest,也就是所有 run 的总用时最小值。解题时重点是利用 List 存储分段时间、用异常阻止已完成的 run 继续添加数据,以及用流式遍历或循环求最小总时间;如果没有任何 run,则返回 Integer.MAX_VALUE。

正文完
 0