如何在数组中查找最短运行的最后一个索引?

时间:2017-05-18 01:02:59

标签: c arrays algorithm sorting

我已经制定了以下逻辑。最短运行:具有相同元素的原始数组的子数组。

// "A" is Array, p is length of a current run, q is global variable that stores lowest run length
procedure(){
    while( i < sizeOfArray){
     if(A[i]==A[i+1]){
     //1.Increment a variable "p" to capture the length of run
      //2. compare p and q and which ever is smaller , is saved into q
      }else{
     //3. What to do here ?
     } 
    }
return q;
}

1 个答案:

答案 0 :(得分:0)

我假设基于代码的“最短运行”意味着数组中所有数字相同的最短序列。下面的算法将找到最短行的最后一个索引。请注意,它会找到第一个最短的运行,因为有多个相同大小的运行。

int A[10] = {1,1,1,1,2,2,2,3,3,3};
int q = INT_MAX, i = 0, p = 1, lastIndex = 0;
while( i != 9 ){ //10 is the size of the array
        if(A[i]==A[i+1]){
                ++p;
        }else{
                if(p < q) {
                        q = p;
                        lastIndex = i;
                }
                p = 1; //reset p, the size of the run should be 1
        }
        i++;
}
return lastIndex; 

请注意,要查找最短的运行,请在运行结束后比较p和q,以便在else语句中对它们进行比较。上面的例子返回6,其中A [6]是2,是最小运行的最后一个索引,大小为3。