Leet Code OJ 26. Remove Duplicates from Sorted Array [Difficulty: Easy]
題目: 
 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.
翻譯: 
 給定一個排序好的數(shù)組,就地移除重復(fù)的元素,來使得每個元素只出現(xiàn)一次,并且返回新的長度。 
 不要分配額外的空間給另一個數(shù)組,你必須完成它在原數(shù)組上,并且只使用常數(shù)級的內(nèi)存。
分析: 
 由于需要移除重復(fù)的元素,所以必須有移動元素的操作。當(dāng)遍歷的i指針指向的元素與上一個元素重復(fù)時,需要采用一個指針nextEmpty來記錄當(dāng)前這個位置(需要被移除的位置,也就是要把后面的元素復(fù)制過來的位置),當(dāng)遍歷到下一個不重復(fù)的元素時,再復(fù)制到這個位置。
代碼:
public class Solution {public int removeDuplicates(int[] nums) {int nextEmpty=1;for(int i=1;i<nums.length;i++){if(nums[i]!=nums[i-1]){nums[nextEmpty]=nums[i];nextEmpty++;}}return nextEmpty;} }總結(jié)
以上是生活随笔為你收集整理的Leet Code OJ 26. Remove Duplicates from Sorted Array [Difficulty: Easy]的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: Leet Code OJ 326. Po
- 下一篇: Leet Code OJ 102. Bi
