lintcode :Remove Duplicates from Sorted Array 删除排序数组中的重复数字

题目:

删除排序数组中的重复数字

给定一个排序数组,在原数组中删除重复出现的数字,使得每个元素只出现一次,并且返回新的数组的长度。

不要使用额外的数组空间,必须在原地没有额外空间的条件下完成。

 样例

给出数组A =[1,1,2],你的函数应该返回长度2,此时A=[1,2]。

解题:

用Python直接搞

Python程序:

class Solution:
"""
@param A: a list of integers
@return an integer
"""
def removeDuplicates(self, A):
# write your code here
ALen =len(A)
i = 0
while i<ALen-1:
if A[i]==A[i+1]:
del A[i+1]
ALen-=1
else:
i+=1
return ALen

总耗时: 755 ms

Java程序:

public class Solution {
/**
* @param A: a array of integers
* @return : return an integer
*/
public int removeDuplicates(int[] nums) {
// write your code here
int i = 0;
int numsLen = nums.length;
while(i<numsLen-1){
if(nums[i]==nums[i+1]){
for(int j=i+1;j<numsLen-1;j++)
nums[j]=nums[j+1];
numsLen-=1;
}else
i+=1;
}
return numsLen;
}
}

总耗时: 2393 ms

时间复杂度:O(n2)
这里原始数据是有序的,时间复杂度降到O(n)

java程序:

public class Solution {
/**
* @param A: a array of integers
* @return : return an integer
*/
public int removeDuplicates(int[] nums) {
// write your code here
if (nums == null || nums.length == 0) {
return 0;
} int size = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != nums[size]) {
nums[++size] = nums[i];
}
}
return size + 1;
}
}

总耗时: 1824 ms

上一篇:numpy数组之读写文件


下一篇:《C#高级编程》读书笔记