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

Leetcode: Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array A = [1,1,2],

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

 

没有想通为什么这个简单的问题竟然不是那么简单,太小看它了,以下是别人的很不错的solution:

Solution: 做法是维护两个指针,一个保留当前有效元素的长度,一个从前往后扫,然后跳过那些重复的元素。因为数组是有序的,所以重复元素一定相邻,不需要额外记录。时间复杂度是O(n),空间复杂度O(1)。代码如下:

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

 

 1 class Solution {
 2     public int removeDuplicates(int[] nums) {
 3         int index = 1;
 4         for (int i = 1; i < nums.length; i ++) {
 5             if (nums[i] != nums[index - 1]) {
 6                 nums[index ++] = nums[i];
 7             }
 8         }
 9         return index;
10     }
11 }

 

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