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