本文共 1198 字,大约阅读时间需要 3 分钟。
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. It doesn’t matter what you leave beyond the returned length.
双指针,慢指针记录被移动的元素
class Solution { public int removeDuplicates(int[] nums) { int letterNums = 1; int prev = 0; for(int i = 1; i < nums.length; i++){ if(nums[i] == nums[prev] && letterNums < 2){ letterNums++; nums[++prev] = nums[i]; } else if(nums[i] != nums[prev]){ nums[++prev] = nums[i]; letterNums = 1; } } return prev+1; }}
leetcode solution 1:
i-2 i [ 1, 1, 2, 2, 2 ] n i-2 i [1, 1, 2, 2, 2] npublic int removeDuplicates(int[] nums) { int i = 0; for (int n : nums) if (i < 2 || n > nums[i-2]) nums[i++] = n; return i;}
转载地址:http://rfqvb.baihongyu.com/