A day leetCode problem - remove the element array --27--

Subject description:

Given an array nums and a value val, you need to place the elements to remove all equal values ​​val, and returns the new length of the array after removal.

Do not use extra space for an array, you must modify the input array in place and completed under the conditions of use O (1) extra space.

Example 1:

Given nums = [3,2,2,3], val = 3

Function should return a new length of 2, and the first two elements nums are 2.

Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2

New function should return the length 5 and the first five nums elements 0,1,3,0,4

Note that these five elements can be in any order

You do not need to consider the array elements beyond the back of the length of the new length.

int removeElement(int arr[],int len,int val)
{
	int count = 0;

	for (int i = 0; i < len; i++)
	{
		if (arr[i] != val)
		{
			arr[count++] = arr[i];
		}
	}
	
	return count;
}



int main()
{
	int arr[] = {0,1,2,2,3,0,4,2};
	int count = removeElement(arr, sizeof(arr)/sizeof(arr[0]), 3);
	printf("%d\n",count);
	for (int i = 0; i < count; i++)
	{
		printf("%d\t",arr[i]);
	}
	printf("\n");
	system("pause");
	return 0;
}
Published 43 original articles · won praise 1 · views 2304

Guess you like

Origin blog.csdn.net/lpl312905509/article/details/103982882