Article Directory
foreword
I kept running just to catch up with myself who had high hopes back
then
提示:以下是本篇文章正文内容,下面案例可供参考
27. Remove elements
Given an array nums and a value val, you need to remove all elements whose value is equal to val in place, and return the new length of the removed array.
Don't use extra array space, you have to use only O(1) extra space and modify the input array in-place.
The order of elements can be changed. You don't need to consider elements in the array beyond the new length.
Method 1: Violent solution method
Time complexity O(N^2)
Space complexity O(1)
According to the worst case, the first one is nums[i]=val. The time complexity is O(N^2). When
we judge that nuns[i]==val, nums[j]=nums[j+1] needs to add the step numsSize–(this step should be no doubt because we cover the same number with the following numbers) but why add i–, you can see the analysis in the figure below
int removeElement(int* nums, int numsSize, int val)
{
int i=0;
for(i=0;i<numsSize;i++)
{
if(nums[i]==val)
{
int j=0;
for(j=i;j<numsSize-1;j++)
{
nums[j]=nums[j+1];
}
numsSize--;
i--;
}
}
return numsSize;
}
Method 2: Space for time
Time complexity O(N)
Space complexity O(N)
int removeElement(int* nums, int numsSize, int val)
{
int* tmp = (int*)malloc(sizeof(int) * numsSize);
int j = 0;
int i = 0;
for (i = 0; i < numsSize; i++)
{
if (nums[i] != val)
{
tmp[j++] = nums[i];
}
}
for (i = 0; i < j; i++)
{
nums[i] = tmp[j];
}
return j;
}
Method 3: Double Pointer
Time complexity O(N)
space complexity O(1)
double pointer means that in the process of traversing objects, instead of using a single pointer to access, two pointers in the same direction (fast and slow pointers) or opposite directions (collision pointers) are used to scan, so as to achieve the corresponding purpose.
int removeElement(int* nums, int numsSize, int val)
{
int src=0;
int dest=0;
while(src<numsSize)
{
if(nums[src]!=val)
{
nums[dest++]=nums[src++];
}
else
{
src++;
}
}
return dest;
}
Summarize
Ending, this is the end of today's Likou daily question content. If you want to know more in the future, please follow me. There are many methods that have not been written. I hope you guys can add them~