Leetcode 26. Remove Duplicates from Sorted Array I and II

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.

本题要求在 sroted list 中 in-place 的进行去重操作,并返回去重后的长度。

思路: 使用双指针。按照本题去重的要求,每个数都不能和前面的数相同,如果出现相同nums[i] == nums[ind]的情况,那么ind不移动。并且会在后边的过程中被替换掉。i 会在 for loop 中自动后移,ind 则不动,在之后的过程中这个第二次出现的4也就会被替换掉。

 Python code

 1 class Solution(object):
 2     def removeDuplicates(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         
 8         n = len(nums)
 9         if n <= 1:
10             return n
11         
12         cur = 0
13         
14         for i in range(1,n):
15             if nums[i] != nums[cur]:
16                 nums[cur+1] = nums[i]
17                 cur += 1
18         
19         return cur + 1 

 C++ code

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
      int size = nums.size();
      if (size <= 1) return size;
      int ind = 0;
      for (int i = 1; i < size; i++) {
          if (nums[ind] != nums[i]) {
              nums[++ind] = nums[i];
          }
      }
        return ind + 1;
    }
};

 

Remove duplicates from sorted array II,唯一的区别是一个数可以重复出现两次。说明一个数它前面的第二个数肯定不同,如果相同的话 ind 不动,这个重复出现的数后来会被替换掉。

 1 class Solution {
 2 public:
 3     int removeDuplicates(vector<int>& nums) {
 4         int size = nums.size();
 5         if (size <= 2) return size;
 6         
 7         int ind = 2;
 8         for (int i = 2; i < size; i++){
 9             if (nums[i] != nums[ind - 2]) {
10                 nums[ind++] = nums[i];
11             }
12         }
13         return ind;
14     }
15 };

 

posted @ 2017-01-08 06:07  lettuan  阅读(198)  评论(0)    收藏  举报