计算数组中连续数字的片段或序列

时间:2014-01-24 00:12:34

标签: arrays algorithm continuous contiguous

假设你有一个整数数组,例如:[0,1,2,5,6,7,9,10,11]。在一个理想的世界中,它们将被排序,但如果算法可以使用未分类的,甚至更好。

我需要知道这个组中有多少“碎片”。想象一下,数组组成一个文件的字节数组;这个文件有多碎片?

在上面的例子中,我统计了3组/片段。

我的目标是将磁盘上的“文件”总数加起来,然后计算“碎片”的总数,然后计算碎片(1 - (files / fragments),我认为.10个文件,10个碎片= 0 %fragmentation - 但是如果每个文件被分成两个,产生20个碎片,那将会产生50%的碎片。

所以我正在寻找的算法需要查看一组int,并计算出有多少连续的数字组。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我想出了这个算法(ObjectiveC)......

-(NSInteger) numberOfFragments {
    NSInteger fragments = 1;

    NSArray *sortedBytes = [_bytes sortedArrayUsingComparator:^NSComparisonResult(GameFileByte *a, GameFileByte *b) {
        return ([a bytePosition] < [b bytePosition]) ? NSOrderedAscending : ([a bytePosition] > [b bytePosition]) ? NSOrderedDescending : NSOrderedSame;
    }];


    NSInteger lastBytePosition = -1;
    for (GameFileByte *byte in sortedBytes) {
        if (lastBytePosition > 0 && ((byte.bytePosition - lastBytePosition) > 1)) {
            fragments++;
        }
        lastBytePosition = byte.bytePosition;
    }


    return fragments;
}

这似乎对我有用......它确保字节顺序正确然后循环通过它们,每当当前字节远离其前一个字节时增加一个计数器。

相关问题