有序数组去重1--Remove Duplicates from Sorted Array

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

 

 

posted @ 2015-07-05 10:12  小榛子  阅读(140)  评论(0编辑  收藏  举报