C 如何找到数组中大于其后所有元素的元素数?
我有一个函数,它接受一个由N个正整数组成的一维数组,并返回大于所有下一个整数的元素数。问题是是否存在一个函数可以在更好的时间内实现这一点?我的代码如下:C 如何找到数组中大于其后所有元素的元素数?,c,algorithm,C,Algorithm,我有一个函数,它接受一个由N个正整数组成的一维数组,并返回大于所有下一个整数的元素数。问题是是否存在一个函数可以在更好的时间内实现这一点?我的代码如下: int count(int *p, int n) { int i, j; int countNo = 0; int flag = 0; for(i = 0; i < n; i++) { flag = 1; for(j = i + 1; j < n; j++) {
int count(int *p, int n) {
int i, j;
int countNo = 0;
int flag = 0;
for(i = 0; i < n; i++) {
flag = 1;
for(j = i + 1; j < n; j++) {
if(p[i] <= p[j]) {
flag = 0;
break;
}
}
if(flag) {
countNo++;
}
}
return countNo;
}
int计数(int*p,int n){
int i,j;
int countNo=0;
int标志=0;
对于(i=0;i 如果(p[i]创建辅助数组aux
:
aux[i] = max{arr[i+1], ... ,arr[n-1] }
它可以通过从右向左扫描阵列在线性时间内完成
现在,您只需要arr[i]>aux[i]
这是在O(n)
中完成的,在数组中向后走,并跟踪当前最大值。每当您找到新的最大值时,该元素大于以下元素。您可以在线性时间内解决此问题(O(n)时间
)。请注意,数组中的最后一个数字始终是符合问题定义的有效数字。因此,函数将始终输出大于等于1的值
要使数组中的任何其他数字成为有效数字,它必须大于或等于数组中该数字之后的最大数字
因此,从右到左遍历数组,跟踪到目前为止找到的最大数,如果当前数大于或等于到目前为止找到的最大数,则递增计数器
时间复杂度:O(n)
空间复杂度:O(1)可以在O(n)
中完成
int计数(int*p,int n){
int i,当前最大值;
int countNo=0;
currentMax=p[n-1];
对于(i=n-1;i>=0;i--){
如果(当前最大值
是的,它可以在O(N)
时间内完成。我将为您提供一种方法来解决这个问题。如果我正确理解了您的问题,您希望在保持顺序的情况下,数组中的元素数大于接下来的所有元素数
因此:
从末端开始遍历数组,即在i=len-1
处,并跟踪遇到的最大元素
可能是这样的:
max = x[len-1] //A sentinel max
//Start a loop from i = len-1 to i = 0;
if(x[i] > max)
max = x[i] //Update max as you encounter elements
//Now consider a situation when we are in the middle of the array at some i = j
{...,x[j],....x[len-1]}
//Right now we have a value of max which is the largest of elements from i=j+1 to len-1
因此,当你遇到一个大于max的x[j]
时,你基本上找到了一个大于下一个所有元素的元素。你可以用一个计数器,在出现这种情况时增加它
显示算法流程的伪代码:
counter = 0
i = length of array x - 1
max = x[i]
i = i-1
while(i>=0){
if(x[i] > max){
max = x[i] //update max
counter++ //update counter
}
i--
}
因此,计数器
最终将具有所需的元素数量
希望我能够向您解释如何进行此操作。编码这应该是一个有趣的练习作为起点。您甚至不需要辅助数组,是吗?@MOehm-Nope,但我发现用这种方法建模更容易。很明显,这种方法正是您想要的(一个元素,arr[I]>max{arr[I+1],…,arr[n-1])
)。如果以后的空间成为问题,则很容易对其进行优化。
Let len = length of array x
{...,x[i],x[i+1]...x[len-1]}
We want the count of all elements x[i] such that x[i]> x[i+1]
and so on till x[len-1]
max = x[len-1] //A sentinel max
//Start a loop from i = len-1 to i = 0;
if(x[i] > max)
max = x[i] //Update max as you encounter elements
//Now consider a situation when we are in the middle of the array at some i = j
{...,x[j],....x[len-1]}
//Right now we have a value of max which is the largest of elements from i=j+1 to len-1
counter = 0
i = length of array x - 1
max = x[i]
i = i-1
while(i>=0){
if(x[i] > max){
max = x[i] //update max
counter++ //update counter
}
i--
}