Leetcode Remove Duplicates from Sorted Array II
2015-04-14 00:03
369 查看
题目地址:https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
题目解析:首先需要一个数组下标用于遍历数组元素;同时在遍历的过程中需要把个数大于2的数字只保留2个,也就是说需要把数组后面的元素往前移,也就是说需要维护一个数组下标,表示后面元素的插入位置;在遍历过程中需要保存当前找到的数字,和之前找到的数字,同时记录数字重复出现的次数,如果一个数字重复次数小于两次则将其直接插入到数组前面(插入索引指向的位置),同时插入索引加1,如果大于两次了,则不插入,插入索引同样不变;一旦发现新元素则将计数器置为1。
题目解答:
题目解析:首先需要一个数组下标用于遍历数组元素;同时在遍历的过程中需要把个数大于2的数字只保留2个,也就是说需要把数组后面的元素往前移,也就是说需要维护一个数组下标,表示后面元素的插入位置;在遍历过程中需要保存当前找到的数字,和之前找到的数字,同时记录数字重复出现的次数,如果一个数字重复次数小于两次则将其直接插入到数组前面(插入索引指向的位置),同时插入索引加1,如果大于两次了,则不插入,插入索引同样不变;一旦发现新元素则将计数器置为1。
题目解答:
public class Solution { public int removeDuplicates(int[] A) { if(A == null || A.length == 0){ return 0; } int count = 1; int curr = A[0]; int insertIndex = 1; int foundIndex = 1; while(foundIndex < A.length){ if(count < 2){ A[insertIndex++] = A[foundIndex]; if (curr == A[foundIndex]) { count++; }else { count = 1; curr = A[foundIndex]; } }else { if (curr != A[foundIndex]){ A[insertIndex++] = A[foundIndex]; curr = A[foundIndex]; count = 1; } } foundIndex++; } return insertIndex; } }
相关文章推荐
- LeetCode题解:Remove Duplicates from Sorted Array I and II
- Remove Duplicates from Sorted Array II - LeetCode 80
- 76 leetcode - Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array I II
- leetcode-Remove Duplicates from Sorted Array II
- 【Leetcode】Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II(在排序数组中删除重复元素)
- [leetcode] python Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II
- LeetCode Remove Duplicates from Sorted Array II
- LeetCode | Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- Leetcode: Remove Duplicates from Sorted Array II
- LeetCode Remove Duplicates from Sorted Array II
- leetcode - Remove Duplicates from Sorted Array I && II
- leetcode-26&80 Remove Duplicates from Sorted Array I & II
- leetcode 虐我篇之(六)Remove Duplicates from Sorted Array II
- Leetcode_c++: Remove Duplicates from Sorted Array II (080)
- Leetcode_Remove Duplicates from Sorted Array II