Leetcode题解14 26. 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.

思路

解这道题的时候,要注意题目中的第一句话,给定的数组已经排好序。所以只需要用ArrayList过滤掉重复元素即可,不需要考虑过滤后数组元素的顺序问题。

public static int removeDuplicates(int[] nums) {
        if(nums.length==0){
 return 0;
        }
        List<Integer> list = new ArrayList<Integer>();
        list.add(nums[0]);
        int count = 1;
        for (int i = 1; i < nums.length; i++) {
            if (list.get(count - 1) != nums[i]) {
                list.add(nums[i]);
                count++;
            }
        }
        count = 0;
        for (int i = 0; i < list.size(); i++) {
            nums[count] = list.get(i);
            count++;
        }
 return count;
    }

你可能感兴趣的:(LeetCode)