https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
给定数组 nums = [1,1,2],
函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。
你不需要考虑数组中超出新长度后面的元素。
给定 nums = [0,0,1,1,1,2,2,3,3,4],
函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。
解题:使用py和Java搞定
傻瓜我想到这个
def removeDuplicates(nums):
"""
:type nums: List[int]
:rtype: int
"""
return len(set(nums))
连题目都没看在原地修改输入数组
思路:遍历列表 如果重复了,就将替换掉
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
i = 0;
for num in nums:
if nums[i] != num:
i +=1
nums[i] = num
return len(nums)
结果不行,我????
考虑数组为空的情况(i初始值为0,由于要求数组长度,故需要加1)
def removeDuplicates(nums):
"""
:type nums: List[int]
:rtype: int
"""
i = 0;
for num in nums:
if nums[i] != num:
i += 1
nums[i] = num
else:
continue
# and中含0,返回0; 均为非0时,返回后一个值,
return len(nums) and i+1
class Solution {
public int removeDuplicates(int[] nums) {
if(nums==null || nums.length == 1){
return nums.length;
}
// 使用双指针
int i = 0;
int j =1;
while(j<nums.length){
// 如果前面 和后面相等
if(nums[i] == nums[j]){
// 继续看看前面是否和后面的后面相等
j++;
}else{
// 不相等 i++
i++;
// 赋值
nums[i] = nums[j];
// j++
j++;
}
}
// 新数组长度
return i+1;
}
}