码迷,mamicode.com
首页 > 编程语言 > 详细

删除有序数组重复项1--Remove Duplicates from Sorted Array

时间:2015-07-05 10:59:32      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/remove-duplicates-from-sorted-array/

Remove Duplicates from Sorted Array

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.

题意:删除重复后,返回数组的长度(因为有序,sorted array 所以重复只会按顺序扎堆出现)

解题思路:使用一个指针j,当i向后遍历数组时,如果遇到与A[j]不同的即收下,将A[i]和A[j+1]交换,同时j=j+1,然后i继续向后遍历。

 1 class Solution:
 2     # @param {integer[]} nums
 3     # @return {integer}
 4     def removeDuplicates(self, nums):
 5         if len(nums)==0:return 0
 6         j=0
 7         for i in range(len(nums)):                  #i依次遍历数组进行判断
 8             if nums[i]!=nums[j]:                    #[0]号数首先收下
 9                 nums[i],nums[j+1]=nums[j+1],nums[i] #(默认重复的数会扎堆在一起)若再次出现不同的数,收下于j后面,即和num[j+1]互换
10                 j=j+1
11         return j+1                                  #注意:j是索引,从0开始,返回长度需要+1

 

 

删除有序数组重复项1--Remove Duplicates from Sorted Array

标签:

原文地址:http://www.cnblogs.com/lzsjy421/p/4621763.html

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