LeetCode之Remove Duplicates from Sorted Array
生活随笔
收集整理的這篇文章主要介紹了
LeetCode之Remove Duplicates from Sorted Array
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
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、實現(xiàn)
代碼一實現(xiàn): 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;} }代碼二實現(xiàn): 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、總結(jié)
方法一總結(jié):我們不能重新申請空間,在原基礎(chǔ)數(shù)組改,我們知道只要說到“連續(xù)數(shù)字”,我么應(yīng)該馬上想到這個數(shù)字和前面的數(shù)字相同,我們在原始數(shù)組上,第一個元素就是新數(shù)組的第一個元素,后面如果新元素和前面的元素不一樣,我們就把這個后面的元素添加在新數(shù)組的末尾。
方法二總結(jié):
記得進(jìn)行i--和length--
總結(jié)
以上是生活随笔為你收集整理的LeetCode之Remove Duplicates from Sorted Array的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode之Max Consecu
- 下一篇: LeetCode之Remove Dupl