• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

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

 

posted @ 2013-04-20 06:16  ying_vincent  阅读(150)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3