题目: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].
源码:Java版本
算法分析:时间复杂度O(n),空间复杂度O(1)
public class Solution {
public int removeDuplicates(int[] A) {
if(A.length==0) {
return 0;
}
int index=0;
for(int i=1;i<A.length;i++) {
if(A[i]!=A[index]) {
A[++index]=A[i];
}
}
return index+1;
}
}
本文介绍了一种在不使用额外空间的情况下从已排序数组中删除重复元素的方法,并提供了Java实现代码。该算法能确保每个元素只出现一次,并返回新长度。通过遍历数组并比较相邻元素来达到目的。
258

被折叠的 条评论
为什么被折叠?



