Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
如果我的列表中可以包含 1 或 2 的值,并且我在运行时获取列表并且我无法修改它,那么如果它确实包含任何其他值,那么检查和报告错误的最佳方法是什么?我是否需要根据 1 和 2 的值检查每个元素,以确保列表中不包含其他值。
如果您从外部来源获取列表,则需要检查列表的每个元素以确保值在正确的范围内。如果您自己制作列表,则可以继承ArrayListor LinkedList,并覆盖变异成员(add、insert等)以检查插入点处的值。
ArrayList
LinkedList
add
insert
是的,如果您收到一个现有列表并想确保它只包含某些值,您必须搜索所有单元格,没有更好的算法。换句话说,在未排序列表中搜索的最佳算法是 O(N)。