【leetcode】26. Remove Duplicates from Sorted Array

来源:互联网 发布:智能问答系统源码 编辑:程序博客网 时间:2024/05/28 05:14

所有题目索引

题目

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.

将已排序数据中不重复的数字都放到数组前端,且输出不重复长度

思路

一个指针指向有序的最后一个位置,一个指针指向还未扫描的数组的开头,遇到跟有序位置不同的,将有序位置加一,把次数放入,继续扫描

代码

java实现

public class Solution {    public int removeDuplicates(int[] nums) {        if(nums.length==0||nums.length==1) return nums.length;        int count=1;        int cur=0;        int nxt=1;        while(nxt<nums.length)        {            if(nums[cur]!=nums[nxt])            {                count++;                cur++;                nums[cur]=nums[nxt];            }            nxt++;        }        return count;    }}

Python实现

class Solution:    # @param {integer[]} nums    # @return {integer}    def removeDuplicates(self, nums):        if len(nums) == 0 or len(nums) == 1:            return len(nums)        count = 1        ready = 0        mess = 1        while mess < len(nums):            if nums[mess] != nums[ready]:                count+=1                ready+=1                nums[ready]=nums[mess]            mess+=1        return count
0 0