leetcode array系列(1) -- remove element
<pre name="code" class="cpp">/* leetcode-remove element
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
*/
#include <iostream>
using namespace std;
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int i = 0;
int j = n;
int length = 0;
for (i = 0; i < n; i++) {
if (A[i] == elem) {
while (j > i) {
j--;
if (A[j] != elem) {
swap(&A[i], &A[j]);
length++;
break;
}
}
}
else {
length++;
}
}
return length;
}
void swap(int *x, int *y) {
int temp = 0;
temp = *x;
*x = *y;
*y = temp;
}
};
void main()
{
int A[4] = { 1, 1, 1, 1 };
//int A[10] = {1, 4, 23, 23, 90, 45, 23, 6, 8, 11};
Solution slt;
//slt.removeElement(A, 10, 23);
slt.removeElement(A, 4, 1);
system("pause");
}