Leetcode 27 Remove Elements

topic

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.

Link: https://leetcode.cn/problems/remove-element

answer

1. Violent solution

Time complexity O(N^2), space complexity O(1)

 

int removeElement(int* nums, int numsSize, int val) 
{
	int size = numsSize;
	for (int i = 0; i < size; i++)
	{
		if (nums[i] == val)
		{
			for (int j = i; j < size; j++)
			{
				nums[j] = nums[j + 1];
			}
			i--;
			size--;
		}
	}
    return size;
}

2. Double pointer

Time complexity O(N), space complexity O(1)

 

int removeElement(int* nums, int numsSize, int val) 
{
	int src = 0;
	int dst = 0;
	while (src < numsSize)
	{
		if (nums[src] != val)
			nums[dst++] = nums[src++];
		else
			src++;
	}
	return dst;
}

 

Guess you like

Origin blog.csdn.net/minLi_/article/details/131437813