Skip to content
Browse files

删除指定元素

  • Loading branch information...
1 parent eb86940 commit 9c53d0d7e921157053fc3e075d1c98a5fa5c8d90 = committed Feb 13, 2014
Showing with 35 additions and 0 deletions.
  1. +35 −0 remove-element.cpp
View
35 remove-element.cpp
@@ -0,0 +1,35 @@
+
+
+// http://oj.leetcode.com/problems/remove-element/
+
+
+// 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.
+
+
+class Solution {
+public:
+ int removeElement(int A[], int n, int elem) {
+ int end = n;
+ for(int i=0;i<end;i++) {
+ while(A[i]==elem && end!=0 && i<end) {
+ end--;
+ mySwap(A, i, end);
+ }
+ }
+
+ int instancesCount = n - end;
+ memset(A+end, 0, instancesCount*sizeof(int));
+
+ return end;
+ }
+
+ void mySwap(int A[], int firstPos, int secondPos) {
+ int tmp = A[firstPos];
+ A[firstPos] = A[secondPos];
+ A[secondPos] = tmp;
+ }
+};

0 comments on commit 9c53d0d

Please sign in to comment.
Something went wrong with that request. Please try again.