26. Remove Duplicates from Sorted Array

Posted optor

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了26. Remove Duplicates from Sorted Array相关的知识,希望对你有一定的参考价值。

原题链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
这道题目是经典的已排序的数组去重问题。之前我有做过看过类似题目的,可以却忘记方法了,所以这次又是写了一个简单粗暴的方法:即遇到重复的元素,对数组进行移位操作:

import java.util.Arrays;

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();

        int[] arr = new int[]{1, 1, 2};
        System.out.println(s.removeDuplicates(arr));
        System.out.println(Arrays.toString(arr));

        arr = new int[]{1, 1, 2, 3, 3, 5, 6, 8, 8};
        System.out.println(s.removeDuplicates(arr));
        System.out.println(Arrays.toString(arr));

        arr = new int[]{1, 1, 1};
        System.out.println(s.removeDuplicates(arr));
        System.out.println(Arrays.toString(arr));
    }

    public int removeDuplicates(int[] nums) {
        if (nums.length < 2) { // nums.length is 0 or 1.
            return nums.length;
        }

        int len = nums.length;

        int mark = 0;
        int temp = nums[mark];
        for (int i = mark + 1; i < len;) {
            if (nums[i] == temp) {
                for (int j = i + 1; j < len; j++) {
                    nums[mark + (j - i)] = nums[j];
                }
                len--;
            } else {
                mark = i;
                temp = nums[mark];
                i++;
            }
        }

        return len;
    }

}

看了下提交结果:66 ms,beats 4.25%
这个结果好尴尬啊,然后我又去看了下官方提供的答案:

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

看完之后只想说:尼玛,官方答案就是牛逼啊!

以上是关于26. Remove Duplicates from Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

26. Remove Duplicates from Sorted Array

26. Remove Duplicates from Sorted Array

#26 Remove Duplicates from Sorted Array

LeetCode OJ 26. Remove Duplicates from Sorted Array

leetcode 26. Remove Duplicates from Sorted Array 80. Remove Duplicates from Sorted Array II

26. Remove Duplicates from Sorted Arrayeasy