-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremoveduplicatearray
More file actions
57 lines (53 loc) · 1.58 KB
/
removeduplicatearray
File metadata and controls
57 lines (53 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# remove duplicates from sorted array
def removeduplicate(intls): #O(n) 空间复杂度略高
length=len(intls)
s=[]
for i in range(0,length-1):
if intls[i+1]==intls[i]:
s.append(i+1)
c=-1
for x in s:
c+=1
intls.pop(x-c)
return intls
print(removeduplicate([1,1,2,2,6,7]))
def removeduplicate2(intls):
return list(set(intls))
print(removeduplicate2([1,1,2,2,6,7]))
def removeduplicate3(intls): #O(n)
for i in intls:
if i==intls[intls.index(i)+1]:
intls.pop(intls.index(i)+1)
return intls
print(removeduplicate3([1,1,2,3,3,5,5,5,7]))
#Follow up for "Remove Duplicates": What if duplicates are allowed at most twice?
# For example, given sorted array A = [1,1,1,2,2,3] , your function should
# return length = 5 , and A is now [1,1,2,2,3]
#python里的字典就像java里的HashMap,以键值对的方式存在并操作,其特点如下
# 通过键来存取,而非偏移量; 键值对是无序的; 键和值可以是任意对象;
def reomveDup(inls,times):
hashtable={}
newls=[]
for i in set(inls):
hashtable[i]=0
for j in inls:
if hashtable[j]>=times:
pass
else:
hashtable[j]+=1
newls.append(j)
return newls
print(reomveDup([1,1,2,2,3,3,3,3,5],2))
#思考为什么需要一个新的列表存储结果而不是直接删除原列表元素
# ls = [1, 2, 3, 4, 5]
# for i in ls:
# if i == 2:
# ls.remove(i)
# else:
# print(i)
#
# 1
# 4
# 5 (输出没有3)
# ls
# [1, 3, 4, 5] (但是里面有3)