• 521. 去除重复元素


    521. 去除重复元素

    中文English

    给一个整数数组,去除重复的元素。

    你应该做这些事

    1.在原数组上操作
    2.将去除重复之后的元素放在数组的开头
    3.返回去除重复元素之后的元素个数

    样例

    例1:

    输入:
    nums = [1,3,1,4,4,2]
    输出:
    [1,3,4,2,?,?]
    4
    
    解释:
    1. 将重复的整数移动到 nums 的尾部 => nums = [1,3,4,2,?,?].
    2. 返回 nums 中唯一整数的数量  => 4.
    事实上我们并不关心你把什么放在了 ? 处, 只关心没有重复整数的部分.
    

    例2:

    输入:
    nums = [1,2,3]
    输出:
    [1,2,3]
    3
    

    挑战

    1.O(n)时间复杂度.
    2.O(nlogn)时间复杂度但没有额外空间

    注意事项

    不需要保持原数组的顺序

     
     
    输入测试数据 (每行一个参数)如何理解测试数据?
    class Solution:
        """
        @param nums: an array of integers
        @return: the number of unique integers
        """
        def deduplication(self, nums):
            # write your code here
            #双指针写法,一个记录,一个走,如果相等,则替换
            length, count = len(nums), 0 
            left, right = 0,length - 1
            dict = {}
    
            #定义主指针
            while left <= right:
                if nums[left] in dict:
                    nums[left], nums[right] = nums[right], nums[left]
                    right -= 1
                else:
                    dict[nums[left]] = True
                    count += 1
                    left += 1 
    
            return  count 
     
  • 相关阅读:
    K-Multiple Free set UVA-11246 (容斥原理)
    RAID! UVA-509 (奇偶校验)
    龙芯 fedora28 安装指南
    Kdenlive简明教程-简单的操作
    Kdenlive简明教程-开始
    Irrelevant Elements UVA-1635 (二项式定理)
    指针的指针笔记
    scanf 函数笔记
    printf 函数笔记
    龙芯 3A4000 Fedora28 安装笔记
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/13196688.html
Copyright © 2020-2023  润新知