1. 程式人生 > >LeetCode. Remove Duplicates from Sorted Array 從排序陣列中刪除重複項

LeetCode. Remove Duplicates from Sorted Array 從排序陣列中刪除重複項

Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory. Example 1:

Given 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 returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4], Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. It doesn’t matter what values are set beyond the returned length.

因為陣列是排好序的,所以重複的元素一定是連續排列的,直接遍歷陣列比較相鄰兩個元素是否相等,找出不相等的所有元素儲存起來,就是我們所求結果,由於題目要求空間複雜度O(1),所以不能另外分配空間,我們可以利用傳遞進來的原陣列空間儲存結果,定義一個counter標記當前可儲存的位置,因為陣列的第0個元素一定是我們需要的結果,所以counter可以直接初始化為1.同時,很容易知道counter也是所有不重複項的length.

C++程式碼如下:

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

Python程式碼如下:

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