• Remove Duplicates from Sorted Array


    1- 问题描述

      Given a sorted array, 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 in place with constant memory.

      For example,


      Given input array 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 new length.


    2- 思路分析

      遍历数组,判断当前值是否和前一个值不一样。若不一样则计数器cnt加1。

      题目并不是仅仅要求输出不同元素个数cnt就完了,还要求原数组的前cnt个数是过滤后的数组。^_^更改提交了很多次,每次都提示Status: Wrong Answer:

      Input: [1,1,2]
      Output: [1,1]
      Expected: [1,2]

      网上找了一下才发现问题所在![1]


    3- Python实现

     1 # -*- coding: utf-8 -*-
     2 
     3 class Solution:
     4     # @param {integer[]} nums
     5     # @return {integer}
     6     def removeDuplicates(self, nums):
     7         if not nums: return 0
     8         cnt = 1    # 统计不同元素个数
     9         for i in range(1, len(nums)):
    10             if nums[i] != nums[i-1]:    # 若当前元素不同于前一个,则将当前元素存入cnt位置,并增加计数
    11                 nums[cnt] = nums[i]
    12                 cnt += 1
    13         return cnt

    [1] leetcode:Remove Duplicates from Sorted Array(去掉数组重复数字,常数空间限制)

  • 相关阅读:
    Free DIY Tour_DP
    找出直系亲属_floyd
    Constructing Roads In JGShining's Kingdom_最长上升子序列
    买卖股票_线性dp
    Common Subsequence_公共子序列
    Doing Homework_状态压缩&&位运算
    猴子选大王
    卡片游戏
    Java 2
    Java 1
  • 原文地址:https://www.cnblogs.com/freyr/p/4505659.html
Copyright © 2020-2023  润新知