80. Remove Duplicates from Sorted Array II

一、题目

  1、审题

  2、分析

    给出一个有序的整数数组,统计总共有多少个元素,其中同一个整数最多只能存在两个,并将统计的所有整数放在数组前头。(只能借助一个额外的空间)

 

二、解答

  1、思路:

    方法一、

      ①、若数组长度 len <= 2, 则直接返回数组长度。

      ②、len > 2时,从下标 i = 2 开始遍历,用 total 记录元素个数

          若 nums[i] != nums[i-2],则此元素为新元素,total++;

          若 nums[i] == nums[i-2],则此元素为重复元素,将 i 后边的元素向前移动一个单元。

(不知道为啥 LeetCode 提交通不过。。。。)

public int removeDuplicates(int[] nums) {
        
        if(nums.length <= 2)
            return nums.length;
        int total = 2;
        for (int i = 2; i < nums.length && nums[i] != -1 ; i++) {
            if(nums[i] != nums[i-2]){
                total++;
            }
            else {    // 前面已经存在 2 个相等的了
                for(int j = i; j < nums.length - 1; j++)
                    nums[j] = nums[j+1];
                for (int j = nums.length-(i+1-total); j < nums.length; j++) { // 将后边不用的赋值 -1
                    nums[j] = -1;
                }
                if(nums[i] == nums[nums.length - 1] )
                    break;    // 结束循环
                --i;
                
            }
        }
        return total;
    }

 

    方法二、

      直接遍历数组元素,用 i 记录数组中存放的出现不超过2次的整数。

      判断方程为:     nums[i-2] != n

      则为符合的整数, nums[i++] = n;

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

 

posted @ 2018-09-23 21:28  skillking2  阅读(123)  评论(0编辑  收藏  举报