leetcode26. Remove Duplicates from Sorted Array

来源:互联网 发布:python股票大数据分析 编辑:程序博客网 时间:2024/06/06 04: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.

思路

用两个指针,一个指针f指向上一个,一个指针s指向下一个。如果f的值小于s的值,则计数。

代码

public class Solution {    public int removeDuplicates(int[] nums) {                if(nums.length <=1){            return nums.length;        }        int count = 1, index = 1;        for( int i = 1; i < nums.length; ){            if(nums[i-1] < nums[i]){                count++;                nums[index] = nums[i];                index ++;                 i++;            }            else{                while(i < nums.length && nums[i - 1] == nums[i]) i++;            }        }        return count;    }}

结果

这里写图片描述

他山之玉

public int removeDuplicates(int[] nums) {    int i = nums.length > 0 ? 1 : 0;    for (int n : nums)        if (n > nums[i-1])            nums[i++] = n;    return i;}
class Solution {    public:    int removeDuplicates(int A[], int n) {        if(n < 2) return n;        int id = 1;        for(int i = 1; i < n; ++i)             if(A[i] != A[i-1]) A[id++] = A[i];        return id;    }};
from collections import OrderedDictclass Solution(object):    def removeDuplicates(self, nums):        nums[:] =  OrderedDict.fromkeys(nums).keys()        return len(nums)
原创粉丝点击