Remove Duplicates from Sorted Array II - LeetCode
2014-02-25 15:37
471 查看
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A =
Your function should return length =
下面是一个不需要用Hash的简单作法,重点是要在原数据集上修改:
What if duplicates are allowed at most twice?
For example,
Given sorted array A =
[1,1,1,2,2,3],
Your function should return length =
5, and A is now
[1,1,2,2,3].
下面是一个不需要用Hash的简单作法,重点是要在原数据集上修改:
public class Solution { public int removeDuplicates(int[] A) { if (A == null || A.length == 0) { return 0; } int size = 0; for (int i = 1; i < A.length; i++) { if (A[i] == A[size] && size > 0 && A[size-1] == A[size]) { continue; } A[++size] = A[i]; } return size + 1; } }
相关文章推荐
- Palindrome Number
- Max Points on a Line
- Evaluate Reverse Polish Notation
- Sort List
- Insertion Sort List
- LRU Cache
- Binary Tree Postorder Traversal
- Binary Tree Preorder Traversal
- Reorder List
- Linked List Cycle
- Linked List Cycle II
- Word Break
- Word Break II
- Copy List with Random Pointer
- Single Number
- Single Number II
- Candy
- Gas Station
- Clone Graph
- Palindrome Partitioning