LeetCode OJ 26. Remove Duplicates from Sorted Array
Posted Black_Knight
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode OJ 26. Remove Duplicates from Sorted Array相关的知识,希望对你有一定的参考价值。
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.
Subscribe to see which companies asked this question
【思路】
举个例子[1,1,1,2,2,2,3,4,5],我的想法就是找到每一节重复数字的长度,然后把后面的数字向前移动,直到遍历到数组最后。
上述例子中,我们从头开始发现有1重复出现了3次,因此我们把1后面的数字向前移动2,变为[1,2,2,2,3,4,5],然后把数组的len变为len-2,重复上面的结果直到遍历到最后,代码如下:
1 public class Solution { 2 public int removeDuplicates(int[] nums) { 3 if(nums==null || nums.length==0) return 0; 4 int len = nums.length; 5 int duplen = 0; 6 for(int i = 0; i < len - 1; i++){ 7 duplen = 0; 8 for(int j = i + 1; j < len; j++){ 9 if(nums[j] == nums[i]) duplen++; 10 else break; 11 } 12 if(duplen > 0){ 13 for(int k = i + duplen + 1; k < len; k++){ 14 nums[k-duplen] = nums[k]; 15 } 16 len = len - duplen; 17 } 18 } 19 return len; 20 } 21 }
以上是关于LeetCode OJ 26. Remove Duplicates from Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode OJ_题解(python):027-Remove Element ArrayEasy
LeetCode OJ 203Remove Linked List Elements
LeetCode OJ Remove Duplicates from Sorted Array II
LeetCode OJ 80. Remove Duplicates from Sorted Array II