LeetCode -- Remove Duplicates from Sorted Array

Question:

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.

Analysis:

问题描述:给定一个排好序的数组,从里面移除重复的元素以保证每个元素只出现一次,然后返回数组的长度。

注意不能另外申请额外的数组空间,应该在constant空间中完成这个问题。

思路:用一个指针count指示当前数组中已经放好了多少个不同的元素,以便当下个不同的元素出现时,只需放入count指针处即可;用一个指针寻找数组中下一个与当前元素不同的元素。

在另外一个地方看到一个博友写的两句话,用来勉励自己。有时候真的是贪多嚼不烂,要冷静下来慢慢的思考问题,不能一味的追求数量与速度!!

1. 当自己面对问题想解题思路的时候,要依靠自己的逻辑思维来”证明/保证”算法的可靠性,不能依靠调试/测试来发现代码的中的bug或逻辑错误。

2. 能一次性写出没有逻辑错误,能够work的代码 是编程能力的体现,也是Google 或 Facebook等大公司面试的必备。

而且发现自己对于这种数组交换排序的问题非常的不顺手,总是不知不觉中把时间复杂度提升一个档次,多做题,多思考!!

Answer:

public class Solution {
    public static int removeDuplicates(int[] nums) {
        if(nums.length == 0 || nums.length == 1)
                return nums.length;
        int count = 1; //如果上面的条件不满足,则一定至少有一个元素能确定在新的数组里
        int current = 1; //当前指针指向第二个元素
        while(current < nums.length) {
                if(nums[current] != nums[current-1]) {
                    nums[count] = nums[current];
                    count ++;
                    current ++;
                } else {
                    current ++;
                }
        }
        return count;
    }
}
原文地址:https://www.cnblogs.com/little-YTMM/p/4819989.html