Leetcode -- Remove Duplicates from Sorted Array
2015-01-03 17:13
363 查看
问题链接:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/
问题描述:
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].
API:public int removeDuplicates(int[] A)
问题分析:这一题其实很简单,就是给一个慢指针去计算答案数目即可,不符合A[i] == A[i - 1]的当前计数器index就可以获得A[i],计数器就可以加一。
给出代码如下:
public int removeDuplicates(int[] A) {
int slow = 1;
for(int i = 1; i < A.length; i++){
if(A[i] != A[i - 1]){
A[slow] = A[i];
slow++;
}
}
return A.length == 0 ? 0 : slow;
}
问题描述:
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].
API:public int removeDuplicates(int[] A)
问题分析:这一题其实很简单,就是给一个慢指针去计算答案数目即可,不符合A[i] == A[i - 1]的当前计数器index就可以获得A[i],计数器就可以加一。
给出代码如下:
public int removeDuplicates(int[] A) {
int slow = 1;
for(int i = 1; i < A.length; i++){
if(A[i] != A[i - 1]){
A[slow] = A[i];
slow++;
}
}
return A.length == 0 ? 0 : slow;
}
相关文章推荐
- leetcode_80题——Remove Duplicates from Sorted Array II(两个指针)
- leetCode---Remove Duplicates from Sorted Array II
- LeetCode刷题笔录 Remove Duplicates From Sorted Array
- [LeetCode]Remove Duplicates from Sorted Array II
- LeetCode Remove Duplicates from Sorted Array
- Leetcode Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array,LeetCode
- LeetCode80 Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- 【LeetCode】C# 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 II 解题报告
- [LeetCode-Algorithms-26] "Remove Duplicates from Sorted Array" (2017.10.12-WEEK6)
- LeetCode 之 Remove Duplicates from Sorted Array
- leetcode [Remove Duplicates from Sorted Array]
- leetcode: Remove Duplicates from Sorted Array
- LeetCode:Remove Duplicates from Sorted Array I&&II
- [leetcode]Remove Duplicates from Sorted Array
- Leetcode 线性表 Remove Duplicates from Sorted Array