Java 语言中提供的数组是用来存储固定大小的同类型元素。数组的元素是通过索引访问的。数组索引从 0 开始,所以索引值从 0 到 arrayRefVar.length-1。
首先,排除数组是null和数组为空两种异常情况;
其次index作为游标用来记录需要替换的后面数据的位置 ,同时记录数组长度;
class Solution {
public int removeDuplicates(int[] nums) {
if(nums==null||nums.length==0){
return 0;
}
int index=1;
for(int i=1;i<nums.length;i++){
if(nums[i]==nums[index-1])
continue;
nums[index]=nums[i];
index++;
}
return index;
}
}
python3:
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
length=len(nums)
count=0
for i in range(1,length):
if nums[count]!= nums[i]:
nums[count+1]=nums[i]
count+=1
return count+1