[Day1]26. Remove Duplicates from Sorted Array

Problem Description:
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 nums = [1,1,2]
Your function should return length = 2, with the first two elements of nums being 1
and 2 respectively. It doesn't matter what you leave beyond the new length.

At first, I didn't notice that the given array is "sorted", so it is a bit harder. My solution of sorted array use 17ms, while top solution takes 13ms.
But, learn more from my "mistake", it is more helpful to solve the unsorted one.

public static int removeDuplicatesUnsorted(int[] nums) {
    int l=nums.length;
    for(int i=0;i<nums.length-1;){
        int same=0;
        for(int j=i+1;j<nums.length;j++){
            if(nums[i]==nums[j]){
                int temp=nums[j];
                nums[j]=nums[i+1+same];
                nums[i+1+same]=temp;
                same++;
                l--;
            }
        }
        i=i+same+1;
    }
    return l;
}

public static int removeDuplicates(int[] nums) {
    int l=1;
    if(nums.length==0)
        return 0;
    for(int i=1;i<nums.length;i++){
        if(nums[i]!=nums[i-1]){
            nums[l]=nums[i];
            l++;
        }
    }
    return l;
}

top solution :

public int removeDuplicatesTop(int[] A) {
    if (A.length==0) return 0;
    int j=0;
    for (int i=0; i<A.length; i++)
        if (A[i]!=A[j]) A[++j]=A[i];
    return ++j;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,789评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,053评论 0 23
  • 哈兹里特—— 死亡是最大的祸害,因为它断绝了希望。 2015年3月7日读卫校的第三年开学了,眼看着就...
    窈窕淑女霞阅读 742评论 1 2
  • 案例一: 有个基督徒问神父:神父,请问祷告的时候,可以吸烟吗? 神父痛斥他:当然不可以。 祷告的时候必须非常虔诚,...
    总在成长阅读 416评论 1 1
  • hdfs 会定期(默认10分钟)使用 du -sk 命令统计BP的大小,在大硬盘机器上该操作耗时将会很长(可能超过...
    breeze_lsw阅读 2,404评论 0 1