程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

[LeetCode]26. Remove Duplicates from Sorted Array ★

发布于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.

python解法

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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.

题后反思:

  1. 列表使用集合去重时数据会变得无序,所以转换成列表需要进行排序

C语言解法

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

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.

题后反思:

  1. 空数组的情况要考虑到

文中都是我个人的理解,如有错误的地方欢迎下方评论告诉我,我及时更正,大家共同进步



所属网站分类: 技术文章 > 博客

作者:38373

链接:https://www.pythonheidong.com/blog/article/53162/67f18d08cf4566f432e6/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

0 0
收藏该文
已收藏

评论内容:(最多支持255个字符)