1. 程式人生 > >LeetCode 26. Remove Duplicates from Sorted Array

LeetCode 26. Remove Duplicates from Sorted Array

Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Tip:題目要求不得使用額外的儲存空間,也就是空間複雜度為O(1),另外解釋了為什麼不需要返回陣列

public class RemoveDuplicatesFromSortedArraySolution {
    public int removeDuplicates(int[] nums) {
        /**
         * 由於陣列有序,相等的資料都放在一起
         */
        int newLen = 0;//不重複資料的指標
        int oldLen = nums.length;

        for (int i = 1; i < oldLen; i++) {
            if (nums[i] != nums[newLen]) {
                nums[++newLen] = nums[i];
            }

        }

        return newLen+1;
    }
}