[Leetcode 1] 26 Remove Duplicates from Sorted Array
2013-04-06 13:04
316 查看
Problem:
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 A =
Your function should return length =
Analysis:
Use two pointers, ptrA always points to the last position of the no-dup array, ptrB traverse the original sorted array, once find an element not equal to *ptrA, increase ptrA and copy it to that position.
The time complexity is O(n) and the sapce complexity is O(n)
Code:
Special Attention:
Pay attention to the special cases such as A is [], A is [1]
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 A =
[1,1,2],
Your function should return length =
2, and A is now
[1,2]
Analysis:
Use two pointers, ptrA always points to the last position of the no-dup array, ptrB traverse the original sorted array, once find an element not equal to *ptrA, increase ptrA and copy it to that position.
The time complexity is O(n) and the sapce complexity is O(n)
Code:
public class Solution { public int removeDuplicates(int[] A) { // Start typing your Java solution below // DO NOT write main() function if (A.length == 0) return 0; int a = 0; for (int b=0; b<A.length; b++) { if (A[a] != A[b]) { A[++a] = A[b]; } } return (a+1); } }
Special Attention:
Pay attention to the special cases such as A is [], A is [1]
相关文章推荐
- leetcode 26. Remove Duplicates from Sorted Array
- Leetcode||26.Remove Duplicates from Sorted Array
- LeetCode-26-Remove Duplicates from Sorted Array(消除已排序数组中的重复元素)
- [leetcode-26]Remove Duplicates from Sorted Array(C)
- LeetCode 26.Remove Duplicates from Sorted Array
- leetcode-26-Remove Duplicates from Sorted Array
- LeetCode 26 Remove Duplicates from Sorted Array(从已排序数组中移除重复元素)
- <LeetCode OJ> 26. Remove Duplicates from Sorted Array
- 【LeetCode】C# 26、Remove Duplicates from Sorted Array
- Leetcode 27. Remove Element & 26. Remove Duplicates from Sorted Array
- leetcode26~Remove Duplicates from Sorted Array
- LeetCode26:Remove Duplicates from Sorted Array
- LeetCode 26. Remove Duplicates from Sorted Array
- [LeetCode] 26 Remove Duplicates from Sorted Array
- [LeetCode]26. Remove Duplicates from Sorted Array I&II
- LeetCode 26. Remove Duplicates from Sorted Array
- LeetCode26 Remove Duplicates from Sorted Array(Python字典妙用)
- 【leetcode】26. Remove Duplicates from Sorted Array
- 算法作业HW25:LeetCode 26. Remove Duplicates from Sorted Array
- LeetCode-26. Remove Duplicates from Sorted Array