在这段代码中,我试图从数组中删除所有出现的指定值。函数应包含三个参数,即数组,数组长度和要搜索的值。每次找到该值时,都应移动该数组以删除该值。
这是我到目前为止所拥有的:
void arrayShift(int arr[], int length, int value){
for(int i = 0; i<length; i++)
{
if(arr[i] == value)
{
for (int k = i; k<length ; k++)
{
arr[k] = arr[k+1];
}
arr[length-1] = 0;
}
}
}
当使用以下值时,代码成功:
int inputarray[] = {10,20,30,40,50,10};
int length = 6;
int value = 10;
//output: 20 30 40 50
int inputarray[] = {6, 7, 8, 9};
int length = 4;
int value = 6;
//ouput: 7 8 9
int inputarray[] = {10,20,30,40,50,60};
int length = 6;
int value = 70;
//output: 10 20 30 40 50 60
但是,该代码在以下情况下不起作用:
int inputarray[] = {9,8,9,9,9,9,6};
int length = 7;
int value = 9;
//what I get: 8 9
//what I want: 8 6
我似乎无法弄清楚为什么在进行迭代时我的代码会失败。
这是您固定的O(n ^ 2)算法。有关线性复杂度的信息,请参见CiaPan的答案。
void arrayShift(int arr[], int length, int value)
{
for(int i = 0; i < length; i++)
{
if(arr[i] == value)
{
for (int k = i; k < length ; k++) // condition should be k + 1 < length, otherwise k + 1 is out of bounds
arr[k] = arr[k + 1];
i--; // you want to decrement i here cause current element has been removed, thus i is already index of the next element
length--; // you should also decrement length
arr[length] = 0;
}
}
}
您还应该返回新的长度,或者通过引用传递长度,以知道之后的尺寸...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句