给定数组
$array = [ 0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0];
对所有0进行分组并将它们表示为起始和结束索引的最快算法是什么?
(即)输出应为(0,5),(10,17)......
答案 0 :(得分:1)
伪代码将是这样的 -
for(int i = 0; i < array.length; i++) {
if(array[i] == 0) {
int left = i;
while(i + 1 < array.length && array[i + 1] == 0) {
i++;
}
// print range [left, i]
}
}
时间复杂度为O(n)
,其中n
为数组长度。空间复杂性是不变的。
答案 1 :(得分:0)
让我以伪代码形式编写多线程方法:
Function ZeroHunter()
Split the array into N segments (where N is multiple of number of threads available)
Create a Dictionary<SegmentNumber, Result>. Let's call it DicResults.
For i = 0 to Number of segments
Result = ProcessSegmentOnNewThread(S)
DicResults.Add(i, Result)
Next
Wait for all threads to complete
ConcatResults(DicResults)
End Function
ProcessSegmentOnNewThread的代码:
Function ProcessSegmentOnNewThread(Segment S)
Create a new thread
List<int, int> lst;
while i < S.Length
if S[i] == 0 Then
NewEntry = lst.Add(i, i)
while i < S.Length and S[i] == 0
NewEntry.End++;
i++
end while
end if
i++
end while
Return the results in the form of List<int, int>
End Function
ConcatResults的代码():
Function ConcatResults(DicResults)
Sort the input dictionary on segment number (the dictionary key that is)
For i = 0 to DicResults.Count - 1
If DicResult[i].End = DicResult[i+1].Start - 1
Set DicResult[i].End = DicResult[i+1].End
Remove DicResult[i+1] from the dictionary
End If
Next
Return DicResult
End Function
需要注意的是,虽然这个算法会击败非常大的数组的非线程算法,但你不应该将它用于较小的数组,因为创建线程和连接结果的开销将超过线程的潜在好处。
答案 2 :(得分:0)
试试这个好友...... !!希望它的罚款:D
#include <stdio.h>
int main()
{
int a[12] = {0,0,0,0,1,1,1,1,0,0,0,0};
int i;
int t = 0;
for( i = 0; i < (int)( sizeof(a) / sizeof(a[0])); i++) {
if(a[i] == t) {
int k = i;
while(i + 1 < (int)( sizeof(a) / sizeof(a[0])) && a[i + 1] == 0) {
i++;
}
printf("range(%d,%d)\n",k,i);
}
}
}