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

【Leetcode】【Array】Remove Duplicates from Sorted Array

【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.

題譯:

給定一個已排序的陣列,請刪除重複的元素,使每個元素只出現一次並返回新長度。
不要為另一個數組分配額外的空間,必須使用常量記憶體。
例如,
給定的輸入陣列陣列= [ 1 ],
你的函式應該返回長度為2的陣列,分別為1和2的第一個元素。不管你離開了什麼新的長度。

Solution:

public class Solution {
    public int removeDuplicates(int[] nums) {
        int i = nums.length>0 ? 1 : 0;
        for(int num : nums){
            if(num>nums[i-1]){
                nums[i]=num;
                i+=1;
            }
        }
        return i;
    }
}

心得:

使用for(int num : nums)句式,順序取出Array、List、Map等集合的元素,是Java語言的一個亮點。