比较对象数组元素的最佳方法(Best way to compare the elements of an array of objects)

编程入门 行业动态 更新时间:2024-10-23 00:29:10
比较对象数组元素的最佳方法(Best way to compare the elements of an array of objects)

所以我有一个由一些具有StartTime和Duration成员变量的对象组成的数组。 startTime变量是格式为“14:20”的字符串,Duration变量是一个数字,表示分钟数。

你们能推荐最好的逻辑来通过阵列和组合重叠元素。 例如,如果数组有两个对象,第一个对象的startTime为“00:00”,持续时间为60,第二个对象的startTime为“08:00”,持续时间为120,则它们将保持独立但是,如果第二个对象的开始时间为“00:30”且持续时间为120,则两者将组合成一个对象,其startTime为“00:00”,持续时间为150。

我已经坚持了一段时间的一般逻辑,因为当组合两个块时,我无法弄清楚如何处理这种情况,但是新的组合块创建了必须处理的新重叠。 我只是在考虑这个错误吗?! 通常我对这种事情很好,但我在这里真的很挣扎。

So I have an array that consists of some number of objects that have both StartTime and Duration member variables. The startTime variable is a string in the format "14:20" and the Duration variable is a number, representing a number of minutes.

Can you guys recommend the best logic for going through the array and combining overlapping elements. For example, if the array had two objects, with the first one having a startTime of "00:00" & duration of 60 and the second object having a startTime of "08:00" & duration of 120 they would be left as separate elements BUT if the second object had a start time of "00:30" and a duration of 120, the two would be combined into one object with a startTime of "00:00" and a duration of 150.

I have been stuck on the general logic of this for some time, because I can't figure how to handle the case when two blocks are combined, but the new combined block creates a new overlap that must be handled. Am I just thinking about this wrong?! Usually I'm good with this sort of thing but am seriously struggling here.

最满意答案

我会通过创建两个树来实现这一点,一个由StartTime索引,另一个由EndTime索引(StartTime + Duration)。 在两个树中搜索重叠的元素。 搜索完成后,任何找到的元素都将从两个树中删除,并且单个新元素(StartTime = minStartTime(searchResult),EndTime = maxEndTime(searchResult))将插入到两个树中。

使用一点额外的存储但我相信这会使你的重叠问题变得微不足道。

(树实现作为练习留下:)

I would do this by creating two trees, one indexed by StartTime and the other indexed by EndTime (StartTime + Duration). Search both trees for elements that overlapped. Once the search was complete any found elements would be removed from both trees and the single new element (StartTime = minStartTime(searchResult), EndTime = maxEndTime(searchResult)) would be inserted into both trees.

Uses a little extra storage but I believe this makes your overlap problem trivial.

(Tree implementation left as an exercise :)

更多推荐

本文发布于:2023-04-28 01:45:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1330281.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   元素   对象   方法   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!