LeetCode – Remove Duplicates from Sorted Array (Java)
2014-05-21 07:50
357 查看
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].
Thoughts
The problem is pretty straightforward. It returns the length of array with unique elements, but the original array need to be changed also. This problem should be reviewed with Remove
Duplicates from Sorted Array II.
Java Solution
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].
Thoughts
The problem is pretty straightforward. It returns the length of array with unique elements, but the original array need to be changed also. This problem should be reviewed with Remove
Duplicates from Sorted Array II.
Java Solution
public class Solution { public int removeDuplicates(int[] A) { if(A.length < 2) return A.length; int j = 0; int i = 1; while(i < A.length){ if(A[i] == A[j]){ i++; }else{ A[++j] = A[i++]; } } return j+1; } }
相关文章推荐
- Java for LeetCode 080 Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array---leetcode 我的java题解
- Leetcode 26. Remove Duplicates from Sorted Array (Easy) (java)
- LeetCode 26. Remove Duplicates from Sorted Array 题解——Java
- LeetCode : Remove Duplicates from Sorted Array [java]
- Remove Duplicates from Sorted Array leetcode java
- [LeetCode][Java] Remove Duplicates from Sorted Array II
- [leetcode]26. Remove Duplicates from Sorted Array(java)
- Leetcode:26. Remove Duplicates from Sorted Array(JAVA)
- [Leetcode] Remove Duplicates from Sorted Array (Java)
- Remove Duplicates from Sorted Array II--leetcode 我的java题解
- [Leetcode] Remove Duplicates from Sorted Array II (Java)
- Remove Duplicates from Sorted Array II leetcode java
- (Java)LeetCode-26. Remove Duplicates from Sorted Array
- LeetCode 第二十六题(Remove Duplicates from Sorted Array) java
- Java [leetcode 26]Remove Duplicates from Sorted Array
- LeetCode – Remove Duplicates from Sorted Array II (Java)
- LeetCode 26 Remove Duplicates from Sorted Array (C,C++,Java,Python)
- [LeetCode-Java]26. Remove Duplicates from Sorted Array
- [LeetCode][Java] Remove Duplicates from Sorted Array