LeetCode Remove Duplicates from Sorted Array

##80. Remove Duplicates from Sorted Array

实际上这种题型分为两种

  1. 在有序数组中删除重复的元素,即数组无重复的数
  2. 在有序数组中删除出现2次以上的数。

方法

遍历数组,对于1,只需保证新加入的数必定比当前数组最后一个数大,更新数组。对于2,只需保证新加入的数必须比当前数组倒数第二个大,更新数组。

  1. 在有序数组中删除重复的元素,即数组无重复的数

    public int removeDuplicates(int[] nums) {
        int i = 0;
        for(int n : nums)
            if(i < 1 || n > nums[i - 1]) 
                nums[i++] = n;
        return i;
    }
    
  2. 在有序数组中删除出现2次以上的数。

    public class Solution {
        public int removeDuplicates(int[] nums) {
            int i = 0;
            for(int n : nums){
                if(i < 2 || n > nums[i-2] ){
                    nums[i] = n;
                    i++;
                }
            }
            return i;
        }
    }
    
Share