標籤:leetcode java remove duplicates fr
題目:
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.
題意:
給定一個排序數組,刪除數組中的重複元素使得數組中的每個元素都只出現一次,返回數組新的長度。
不要為新的數組分配空間,你必須使用常數空間。
比如:
給定輸入數組 nums = [1,1,2],
你所寫的函數需要返回長度2,數組中的兩個元素分別為1 and 2。數組中的超過這個長度的元素無關緊要。
演算法分析:
利用雙指標
* 前後兩個指標,前指標固定不動,後指標去搜尋
* 直到後指標指到與前指標不同的元素上,這時統計到了第二個不同元素,i++;
* 前指標重設到現在後指標的位置
* 重複上述過程,能夠統計出不同的元素的總個數,而且原數組中的前i個元素即為這i個互為不同的元素
AC代碼:
/** * 前後兩個指標,前指標固定不動,後指標去搜尋 * 直到後指標指到與前指標不同的元素上,這時統計到了第二個不同元素,i++; * 前指標重設到現在後指標的位置 * 重複上述過程,能夠統計出不同的元素的總個數,而且原數組中的前i個元素即為這i個互為不同的元素 */ public class Solution { public int removeDuplicates(int[] nums) {if(nums.length==0) return 0;int startindex = 0;int endindex = 0;int i=0; while(endindex<nums.length) { while(endindex<nums.length) { if(nums[startindex]==nums[endindex]) endindex++; else { break; } } nums[i]= nums[startindex];startindex=endindex;i++; }return i; }}
著作權聲明:本文為博主原創文章,轉載註明出處
[LeetCode][Java] Remove Duplicates from Sorted Array