LeetCode Remove Duplicates from Sorted Array
2014-11-03 20:00
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 =
Your function should return length =
题意:从排序的数组中删除重复的元素,使得每个元素只出现一次,返回新的数组的长度
思路:将新的数组的索引cnt=0,将数组的第一个元素赋值,即a[cnt] = a[0],然后从1到len遍历数组,如果a[i] == a[cnt - 1]继续
public class Solution {
public int removeDuplicates(int[] A) {
if (A.length == 0) return 0;
int cnt = 0;
A[cnt++] = A[0];
for (int i = 1, len = A.length; i < len; i++) {
if (A[i] == A[cnt - 1]) continue;
else A[cnt++] = A[i];
}
return cnt;
}
}
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].
题意:从排序的数组中删除重复的元素,使得每个元素只出现一次,返回新的数组的长度
思路:将新的数组的索引cnt=0,将数组的第一个元素赋值,即a[cnt] = a[0],然后从1到len遍历数组,如果a[i] == a[cnt - 1]继续
public class Solution {
public int removeDuplicates(int[] A) {
if (A.length == 0) return 0;
int cnt = 0;
A[cnt++] = A[0];
for (int i = 1, len = A.length; i < len; i++) {
if (A[i] == A[cnt - 1]) continue;
else A[cnt++] = A[i];
}
return cnt;
}
}
相关文章推荐
- 【leetcode c++】26 Remove Duplicates from Sorted Array
- LeetCode-26-Remove Duplicates from Sorted Array
- LeetCode 026 Remove Duplicates from Sorted Array
- LeetCode 26 Remove Duplicates from Sorted Array (C,C++,Java,Python)
- LeetCode-Array-26 Remove Duplicates from Sorted Array
- 【Leetcode】之Remove Duplicates from Sorted Array II
- LeetCode | Remove Duplicates from Sorted Array
- LeetCode – Remove Duplicates from Sorted Array (Java)
- LeetCode:Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array -- leetcode
- [LeetCode] Remove Duplicates from Sorted Array II 解题报告
- leetcode 26. Remove Duplicates from Sorted Array
- Leetcode 27. Remove Element & 26. Remove Duplicates from Sorted Array
- leetcode之26. Remove Duplicates from Sorted Array(C++解法)
- LeetCode - 26. Remove Duplicates from Sorted Array
- LeetCode:Remove Duplicates from Sorted Array
- LeetCode Remove Duplicates from Sorted Array II
- leetcode 26 Remove Duplicates from Sorted Array
- LeetCode | Remove Duplicates from Sorted Array II