LintCode101 · Remove Duplicates from Sorted Array II (数组原地修改好题)

101 · Remove Duplicates from Sorted Array II
Algorithms

Description
Given a sorted array nums, logically remove the duplicates in place and return the length len, such that each element appear at most twice in the first len elements of the original array nums.
If a number appears more than two times, then keep the number appears twice in array after remove.
Need to operate in the original array

Example
Example 1:

Input:

array = []
Output:

0
Explanation:

Empty array, length is 0.

Example 2:

Input:

array = [1,1,1,2,2,3]
Output:

5
Explanation:

the length is 5: [1,1,2,2,3]

解法1:
为什么是 if (nums[left - 2] != nums[right]) ?
举例:如果数组是[6,6,6,6,6,7,7,7], right=5的时候(nums[5]=7), left = 2,那么我们看如果nums[left-2]!=7,那么说明需要把nums[2]改成7,同时left++.

class Solution {
public:
    /**
     * @param A: a list of integers
     * @return : return an integer
     */
    int removeDuplicates(vector<int> &nums) {
        int n = nums.size();
        if (n < 2) return n;
        int left = 2, right = 2;
        while (right < n) {
            if (nums[left - 2] != nums[right]) {
                nums[left] = nums[right];
                left++;
            }
            right++;
        }
        return left;
    }
};

你可能感兴趣的:(数据结构,算法)