【问题标题】:time and performance complexity in nested for loops嵌套 for 循环中的时间和性能复杂度
【发布时间】:2015-11-05 17:34:37
【问题描述】:

我有一个像下面这样的对象:

1 [country1, state1, district1, schoolName1, studentName1]
2 [country1, state1, district1, schoolName1, studentName2]
3 [country1, state1, district1, schoolName2, studentName1]
4 [country1, state1, district1, schoolName2, studentName2]
5 [country1, state1, district2, schoolName1, studentName1]
6 [country1, state1, district2, schoolName1, studentName2]
.
.
.
1000 [country3, state4, district2, schoolName2, studentName1]
1001 [country3, state4, district2, schoolName2, studentName2]
.
.

现在我想隔离如下:

[country1]
    [state1]
        [district1]
                [schoolname1]
                    [studentname1,studentName2,...]
                [schoolname2]
                    [studentname1,studentName2,...]
                .
                .
        [district2]
                .
                .
[country2]
    [state1]
        [district1]
                [schoolname1]
                    [studentname1,studentName2,...]
                [schoolname2]
                    [studentname1,studentName2,...]
                .
                .
        [district2]
                [schoolName1]
                    .
                    .

据我所知,我可以使用嵌套的for 循环。但它消耗更多的时间和性能。我知道这是个坏主意。如果您遇到过这种情况,请分享您的经验以解决此问题。

【问题讨论】:

  • [some text here] 是什么意思?这是一个数据结构还是你想打印这样的文本?
  • 对不起。我需要这样的对象。例如:1个国家对象应该有嵌套的状态对象,一个状态对象应该有多个地区对象。等

标签: java performance for-loop time-complexity


【解决方案1】:

您的任务的最小复杂性(您可能获得的最佳性能)取决于您输入的规模,即number of rows * number of items in each row。您无法变得更好,因为您至少必须读取所有输入一次,因为您需要所有数据。

同时,您的任务应该能够应对这种复杂性。

因此,如果您使用两个嵌套循环(一个用于行,另一个用于列),那么您做得很好 - 这将执行大约正确数量的操作。如果您使用的嵌套循环与列的数量一样多,那么您的工作就很糟糕(rows ^ columns 而不仅仅是rows * columns)并且应该尝试不同的方法 - 对于这样的任务,您只需要阅读每行一次,对其进行处理并将结果添加到层次结构中的正确位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 2022-01-21
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多