1、题目
tag:easy array
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/
2、实现
分析:空间要求就地O(1),时间复杂度O(n)
两种语言时间差辣么多 O__O "…
Java
class Solution {
public int removeDuplicates(int[] nums) {
int len=nums.length;
if(len==1){
return len;
}
int i=0;
for(int j=1;j<len;j++){
if(nums[i]!=nums[j]){
nums[i+1]=nums[j];
i++;
}
}
return i+1;
}
}
python
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n=len(nums)
if n in (0,1):
return n
i=0
j=1
while(j<n):
if nums[i]!=nums[j]:
nums[i+1]=nums[j]
i=i+1
j=j+1
return i+1
3、本题用到知识点
Java | Python | |
循环 | for(;;) | for i in range(n) 0<=i<n while() |
数组长度 | arr.length | len(arr) |
+1 | i++ | i=i+1
python不支持n++这种写法。 因此,正确的自增操作应该 n = n + 1 或者 n += 1。 |