LeetCode之Remove Duplicates from Sorted Array
生活随笔
收集整理的這篇文章主要介紹了
LeetCode之Remove Duplicates from Sorted Array
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、題目
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.
2、實現
代碼一實現: public class Solution {public int removeDuplicates(int[] a) {if (null == a) {return 0;}int length = a.length;// if (length > 0)// a[0] = a[0];int newLen = 1;for (int i = 1; i < length; ++i) {if (a[i] != a[i - 1]) {a[newLen++] = a[i];}}return newLen;} }代碼二實現: public int removeDuplicates1(int[] a) {if (a == null || a.length == 0) {return 0;}int length = a.length;for (int i = 0; i < length - 1; ++i) {if (a[i] == a[i + 1]) {for (int j = i + 1; j < length - 1; j++) {a[j] = a[j + 1];}i--;length--;}}return length;}
?
3、總結
方法一總結:我們不能重新申請空間,在原基礎數組改,我們知道只要說到“連續數字”,我么應該馬上想到這個數字和前面的數字相同,我們在原始數組上,第一個元素就是新數組的第一個元素,后面如果新元素和前面的元素不一樣,我們就把這個后面的元素添加在新數組的末尾。
方法二總結:
記得進行i--和length--
總結
以上是生活随笔為你收集整理的LeetCode之Remove Duplicates from Sorted Array的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode之Max Consecu
- 下一篇: LeetCode之Remove Dupl