码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 26. Remove Duplicates from Sorted Array

时间:2017-05-01 22:20:56      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:ant   ges   https   func   ica   leave   思路   数组   png   

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.

 

Subscribe to see which companies asked this question.

题目大意:给定一个有序数组,删除重复元素,返回新的数组的长度。不为另一个数组分配额外空间,必须用常量内存做到这一点。
解题思路:遍历数组,如果遇到跟前一个元素相同的元素就跳过,遇到不重复的元素则将count加1.原本以为只要统计新数组长度就行了,结果一直报错。原来还要删除元素后数组要按新的元素排列才行。因此修改了一下代码。原本python很方便的可以用for i in nums[1:]这种方式遍历数组的所有值,现在只能够用下标的方式遍历。
技术分享

 

class Solution(object):
  def removeDuplicates(self, nums):
  """
  :type nums: List[int]
  :rtype: int
  """
  count = 1
  index = 1
  if len(nums) <= 1:
    return len(nums)
  for i in range(1,len(nums)):
  if(nums[i] != nums[i - 1]):
    nums[index] = nums[i]
    count += 1
    index += 1
  return count

 
 

LeetCode 26. Remove Duplicates from Sorted Array

标签:ant   ges   https   func   ica   leave   思路   数组   png   

原文地址:http://www.cnblogs.com/fangdai/p/6792777.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!