leetcode 26. Remove Duplicates from Sorted Array从排序数组中移出重复元素(双指针)

来源:互联网 发布:速卖通翻译软件 编辑:程序博客网 时间:2024/05/21 12:50

问题描述:

  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 by modifying the input array in-place with O(1) extra memory.


这里写图片描述

思路:

  因为不能使用额外空间,所以使用双指针,一个个向后搜索并排列。len代表目前的长度,i去进行一个个的搜索。

代码:

class Solution {    public int removeDuplicates(int[] nums) {        if(nums == null) return 0;        int len = 1;        for(int i = 1; i < nums.length; i++){            if(nums[i] != nums[i-1]){                if(nums[i] != nums[len])                    nums[len] = nums[i];                len++;            }                    }        return len;            }}
阅读全文
0 0
原创粉丝点击