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

Leetcode: Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array A = [1,1,1,2,2,3],

Your function should return length = 5, and A is now [1,1,2,2,3].

第二遍做法:

 1 public class Solution {
 2     public int removeDuplicates(int[] A) {
 3         if (A == null || A.length == 0) return 0;
 4         int len = 1;
 5         int count = 1;
 6         for (int i=1; i<A.length; i++) {
 7             if (A[i] == A[len-1] && count < 2) {
 8                 A[len] = A[i];
 9                 len++;
10                 count++;
11             } 
12             else if (A[i] != A[len-1]) {
13                 A[len] = A[i];
14                 len++;
15                 count = 1;
16             }
17         }
18         A = Arrays.copyOf(A, len);
19         return len;
20     }
21 }

 

posted @ 2014-05-21 12:33  neverlandly  阅读(245)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3