zoukankan      html  css  js  c++  java
  • 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 }
     
  • 相关阅读:
    winform导入导出excel,后台动态添加控件
    asp.net 导入excel文件
    asp.net gridview动态添加列,并获取其数据;
    中转Http请求
    窗体托盘后台运行
    后台程序完成指定任务
    死锁查看
    异步等待(ManualResetEvent
    C#后台程序重启IIS,发邮件通知
    mybatis入门视频总结
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3702707.html
Copyright © 2011-2022 走看看