LeetCode解题报告--Remove Duplicates from Sorted Array

题目:

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.

分析:移除给定数组里重复的元素,返回移除后数组的长度。题意要求不能开创新的数组,则须在原来的数组上做文章,即基本解题思路是,遍历整个数组,将重复的元素直接用后面的元素覆盖,直接在原来的数组上构造新数组,新的数组前count个元素是只包含不重复的单一元素。

Java 代码 Accepted:

import java.util.Arrays;

public class RemoveDuplicatesFromSortedArray {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] nums = new int[]{1,1,2};
        System.out.println("nums: " + removeDuplicates(nums));
        System.out.println("---------------------");
        int[] nums1 = new int[]{};
        System.out.println("nums1: " + removeDuplicates(nums1));
        System.out.println("---------------------");
        int[] nums2 = new int[]{1,1,1,1};
        System.out.println("nums2: " + removeDuplicates(nums2));
        System.out.println("---------------------");
        int[] nums3 = new int[]{1,2,3,4,4,5,6,7,8,9};
        System.out.println("nums3 " + removeDuplicates(nums3));
    }

    public static int removeDuplicates(int [] nums){

        //Special case:
        if(nums.length == 0 || nums == null)
            return 0;

        //Normal case:
        int count = 0;

        for(int i = 0;i < nums.length;i ++){
            if(nums[i] != nums[count]){
                nums[++count] = nums[i];

                System.out.println(Arrays.toString(nums) + " : " + count);
            }
        }
        return count + 1;
    }
}

结果:具体过程演示:

[1, 2, 2] : 1
nums: 2
---------------------
[1, 2, 2] : 1
nums: 2
---------------------
nums1: 0
---------------------
nums2: 1
---------------------
[1, 2, 3, 4, 4, 5, 6, 7, 8, 9] : 1
[1, 2, 3, 4, 4, 5, 6, 7, 8, 9] : 2
[1, 2, 3, 4, 4, 5, 6, 7, 8, 9] : 3
[1, 2, 3, 4, 5, 5, 6, 7, 8, 9] : 4
[1, 2, 3, 4, 5, 6, 6, 7, 8, 9] : 5
[1, 2, 3, 4, 5, 6, 7, 7, 8, 9] : 6
[1, 2, 3, 4, 5, 6, 7, 8, 8, 9] : 7
[1, 2, 3, 4, 5, 6, 7, 8, 9, 9] : 8
nums3 9
nums1: 0
---------------------
nums2: 1
---------------------
[1, 2, 3, 4, 4, 5, 6, 7, 8, 9] : 1
[1, 2, 3, 4, 4, 5, 6, 7, 8, 9] : 2
[1, 2, 3, 4, 4, 5, 6, 7, 8, 9] : 3
[1, 2, 3, 4, 5, 5, 6, 7, 8, 9] : 4
[1, 2, 3, 4, 5, 6, 6, 7, 8, 9] : 5
[1, 2, 3, 4, 5, 6, 7, 7, 8, 9] : 6
[1, 2, 3, 4, 5, 6, 7, 8, 8, 9] : 7
[1, 2, 3, 4, 5, 6, 7, 8, 9, 9] : 8
nums3 9

延伸:如果给定数组允许最多重复出现两个元素,代码如何实现?
参考:http://www.programcreek.com/2013/01/leetcode-remove-duplicates-from-sorted-array-ii-java/

你可能感兴趣的:(LeetCode解题报告,LeetCode,解题报告,leetcode,算法)