zoukankan      html  css  js  c++  java
  • leetcode26 Remove Duplicates from Sorted Array

     1 """
     2 Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
     3 Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
     4 Example 1:
     5 Given nums = [1,1,2],
     6 Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
     7 It doesn't matter what you leave beyond the returned length.
     8 Example 2:
     9 Given nums = [0,0,1,1,1,2,2,3,3,4],
    10 Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
    11 It doesn't matter what values are set beyond the returned length.
    12 """
    13 """
    14 本题的关键是不用新开辟数组
    15 而是用一个指针来在原数组上存放结果
    16 """
    17 
    18 class Solution:
    19     def removeDuplicates(self, nums):
    20         if not nums:
    21             return 0
    22         j = 0 #用来借用原数组上的空间存答案数组的指针
    23         for i in range(1, len(nums)):
    24             if nums[i] != nums[i-1]:
    25                 j += 1
    26                 nums[j] = nums[i]
    27         return j+1
  • 相关阅读:
    js 数据格式化
    js 获取URL中参数
    微信公众平台JSSDK开发
    js 日期格式化及日期增减
    一句话的设计模式
    微信小程序开源项目库汇总
    bash 配置文件
    centos 设置时间为北京时间
    数据库一般数据的查询操作
    linux tmux 工具使用 tmux.conf 文件
  • 原文地址:https://www.cnblogs.com/yawenw/p/12337730.html
Copyright © 2011-2022 走看看