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 }
     
  • 相关阅读:
    zendstuido10 配置spket插件
    Extjs各版本的下载链接
    主题:Android、iPhone和Java三个平台一致的加密工具
    TestDisk 恢复rm -rf 的文件
    java实现定时任务的三种方法
    mac 下安装 lua5.3 + cjson
    Mac OS X 上Lua的安装方法
    Channel States
    JSON常见操作
    微信小程序——获取元素的宽高等属性
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3702707.html
Copyright © 2011-2022 走看看