LeetCode: Remove Element

简单题, 一次过

 1 class Solution {

 2 public:

 3     int removeElement(int A[], int n, int elem) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         int dup = 0;

 7         for (int i = 0; i < n; i++) {

 8             while (A[i] == elem && i+dup < n) {

 9                 dup++;

10                 for (int j = i; j < n-1; j++) A[j] = A[j+1];

11             }

12         }

13         return n - dup;

14     }

15 };

 再贴一个时间复杂度低但是空间复杂度高的

 1 class Solution {

 2 public:

 3     int removeElement(int A[], int n, int elem) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         vector<int> B;

 7         for (int i = 0; i < n; i++) {

 8             if (A[i] == elem) continue;

 9             B.push_back(A[i]);

10         }

11         for (int i = 0; i < B.size(); i++) A[i] = B[i];

12         return B.size();

13     }

14 };

 C#

 1 public class Solution {

 2     public int RemoveElement(int[] nums, int val) {

 3         List<int> ans = new List<int>();

 4         for (int i = 0; i < nums.Length; i++) {

 5             if (nums[i] == val) continue;

 6             ans.Add(nums[i]);

 7         }

 8         for (int i = 0; i < ans.Count; i++) nums[i] = ans[i];

 9         return ans.Count;

10     }

11 }
View Code

 

你可能感兴趣的:(LeetCode)