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

Remove Duplicates from Sorted Array

mov turn 通過 must modifying sorted alloc int 進行

問題

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

代碼

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

因為是有序的數組所以可以通過foreach循環直接進行比較。

Remove Duplicates from Sorted Array