LeetCode-Java题解 26. Remove Duplicates from Sorted Array

题目地址:26. Remove Duplicates from Sorted Array
解题思路:有了上一题的基础,看见这道题的时候,应该立刻想到双指针法。但不同于上一题的是,这次需要将非重复元素移动到数组的开端,需要注意的点就是数组是一个有序数组,重复数字必定是相邻的,抓好这个重点,这道题就不难解了。

class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int head = 0;
        int tail = 1;
        while (tail < nums.length) {
            if (nums[head] != nums[tail]) {
                nums[head + 1] = nums[tail];
                head++;
            } else {
                tail++;
            }
        }
        return head+1;
    }
}
posted @ 2022-02-07 11:59  古宇  阅读(22)  评论(0编辑  收藏  举报

欢迎来刀