这是一道面试题。问题:从原地数组中删除重复项:
public class Solution4 {
public static void main(String[] args) {
int[] a = {1,1,2,3,4,5,6,6,7,8};
int countwithoutDuplicates = lengthofarraywithoutDuplicates(a);
for(int i = 0 ; i < countwithoutDuplicates ; i++) {
System.out.println(a[i] + " ");
}
}
private static int lengthofarraywithoutDuplicates(int[] a) {
int countwithoutDuplicates = 1 ;
for (int i = 1; i < a.length; i++) {
if( a[i] != a[i-1] ) {
a[countwithoutDuplicates++] = a[i];
}//if
}//for
System.out.println("length of array withpout duplicates = >" + countwithoutDuplicates);
return countwithoutDuplicates;
}//lengthofarraywithoutDuplicates
}
在 Python 中:
def lengthwithoutduplicates(nums):
if not nums: return 0
if len(nums) == 1:return 1
# moving backwards from last element i.e.len(a) -1 to first element 0 and step is -1
for i in range(len(nums)-1,0,-1):
# delete the repeated element
if nums[i] == nums[i-1]: del nums[i]
# store the new length of the array without the duplicates in a variable
# and return the variable
l = len(a)
return l
a = [1, 1, 2, 3, 4, 5, 6, 6, 7, 8];
l = lengthwithoutduplicates(a)
for i in range(1,l):print(i)
在 Python 中:使用枚举的列表理解
a = [1, 1, 2, 3, 4, 5, 6, 6, 7, 8]
aa = [ ch for i, ch in enumerate(a) if ch not in a[:i] ]
print(aa) # output => [1, 2, 3, 4, 5, 6, 7, 8]