发布于2019-08-22 17:33 阅读(769) 评论(0) 点赞(0) 收藏(2)
Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.
题目大意:计算一个排好序的数组中不重复元素的个数n,并将个数返回给调用函数,但是同时需要改变数组中元素的排列顺序(不能重新申请内存存储这些数据),最终比较的结果是数组的前n个元素,前n个元素就是n个排好序的数。
Example 1:
Given 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 returned length.
Example 2:
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn’t matter what values are set beyond the returned length.
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
num = sorted(list(set(nums)))
for i, n in enumerate(num):
nums[i] = n
return len(num)
Runtime: 96 ms, faster than 76.82% of Python3 online submissions for Remove Duplicates from Sorted Array.
Memory Usage: 15.6 MB, less than 5.01% of Python3 online submissions for Remove Duplicates from Sorted Array.
题后反思:
int removeDuplicates(int* nums, int numsSize){
int n = 1 ;
if(numsSize == 0)
{
return 0;
}
for(int i = 1; i < numsSize;i++)
{
if(nums[i-1] != nums[i])
{
nums[n ++] = nums[i];
}
}
return n;
}
Runtime: 20 ms, faster than 69.83% of C online submissions for Remove Duplicates from Sorted Array.
Memory Usage: 9.6 MB, less than 31.67% of C online submissions for Remove Duplicates from Sorted Array.
题后反思:
文中都是我个人的理解,如有错误的地方欢迎下方评论告诉我,我及时更正,大家共同进步
作者:38373
链接:https://www.pythonheidong.com/blog/article/53162/67f18d08cf4566f432e6/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!