C Function to Remove Element from Array: Efficient Implementation
This is a C function that takes an integer array 'nums', its size 'numsSize', and a value 'val' to remove from the array. The function iterates through the array and checks if each element is equal to 'val'. If it's not equal to 'val', it's added to a new array at index 'k'. After iterating through the entire array, the function returns 'k', which is the number of elements in the new array that do not contain 'val'. Essentially, this function removes all occurrences of 'val' from the array by shifting all non-'val' elements to the front of the array.
int removeElement(int* nums, int numsSize, int val) {
int k = 0;
for(int i=0;i<numsSize;i++) {
if(nums[i] != val) nums[k++] = nums[i];
}
return k;
}
原文地址: http://www.cveoy.top/t/topic/mJar 著作权归作者所有。请勿转载和采集!