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

LeetCode: Remove Duplicates from Sorted Array

很奇怪这种小问题会多数次过。。太小看他了

 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 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-1-dup; i++) {
 8             if (A[i] != A[i+1]) continue;
 9             for (int j = i; j < n-dup; j++) A[j] = A[j+1];
10             dup++;
11             i--;
12         }
13         return n-dup;
14     }
15 };

 下面段代码更好

 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         if (n < 2) return n;
 5         int c = 0;
 6         for (int i = 0; i < n; ++i) {
 7             if (A[c] != A[i]) A[++c] = A[i];
 8         }
 9         return c+1;
10     }
11 };

 C#

 1 public class Solution {
 2     public int RemoveDuplicates(int[] nums) {
 3         if (nums.Length < 2) return nums.Length;
 4         int c = 0;
 5         for (int i = 0; i < nums.Length; i++) {
 6             if (nums[c] != nums[i]) nums[++c] = nums[i];
 7         }
 8         return c + 1;
 9     }
10 }
View Code

 

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