[26] Remove Duplicates from Sorted Array

来源:互联网 发布:学java看什么书 编辑:程序博客网 时间:2024/04/30 09:40

1. 题目描述

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.

题目意思为给定一个排好序的数组,消除其中重复的元素,并且返回新数组的长度,操作在原数组上进行,且并不在乎超过新数组长度的部分为什么元素。

2. 解题思路

题目的大体与之前做过的消除链表中重复元素相似,不同的是,链表可以通过一个指针的修改直接将一串元素清除,而数组元素是需要进行数组内部的移动操作才能得到新的数组。那么我最爱的方法又来了,画图。
26
验证是否重复无非就是比较当前这个和下一个是否相等,如果相等下一个元素就不要了。所以我们使用两个指针,一个指针保存当前最后一个不重复的节点的位置,另一个指针向后移动,与当前值进行比较,不相等时就将值移动到第一个指针的后面一个元素位置,相等就继续后移不作操作。因为在这个题中,不要求新数组长度外的元素清空,所以做到上图就结束了。

3. Code

public class Solution {    public int removeDuplicates(int[] nums) {        // 数组长度为0或1,不会有重复的元素        if(nums.length <= 1)        {            return nums.length;        }        // 当前数组中元素数量        int num = 1;        for(int i = 0, j = 1; j < nums.length; ++j)        {            // 如果相等,i不动j后移            if(nums[i] == nums[j])            {                 continue;            }            // 如果不相等,i后移,i位置值等于j位置值            nums[++i] = nums[j];            ++num;  // 数组中元素数量加1         }        return num;    }}
0 0
原创粉丝点击