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- 思路分析
遍历数组,判断当前值是否和前一个值不一样。若不一样则计数器cnt加1。
题目并不是仅仅要求输出不同元素个数cnt就完了,还要求原数组的前cnt个数是过滤后的数组。^_^更改提交了很多次,每次都提示Status: Wrong Answer:
Input: [1,1,2]
Output: [1,1] Expected: [1,2]网上找了一下才发现问题所在![1]
3- Python实现
1 # -*- coding: utf-8 -*- 2 3 class Solution: 4 # @param {integer[]} nums 5 # @return {integer} 6 def removeDuplicates(self, nums): 7 if not nums: return 0 8 cnt = 1 # 统计不同元素个数 9 for i in range(1, len(nums)):10 if nums[i] != nums[i-1]: # 若当前元素不同于前一个,则将当前元素存入cnt位置,并增加计数11 nums[cnt] = nums[i]12 cnt += 113 return cnt
[1]