版权声明:版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Strive_0902/article/details/82694517
实现如下
第一个函数:找出重复的元素
第二个函数:找出重复的元素,并输出重复的次数
class duplicate:
def duplicate_1(self,array):
d = {}
res = []
for i in array:
d[i] =d.get(i,0)+1
for j in d.keys():
if d[j]>1:
res.append(j)
return res
def duplicate_2(self,array):
d = {}
res = {}
for i in array:
d[i] =d.get(i,0)+1
for j in d.keys():
if d[j]>1:
res[j] = d[j]
return res
if __name__ =='__main__':
test = duplicate()
print(test.duplicate_1([2,1,4,6,3,2,6,8,3]))
print(test.duplicate_2('aaacdrtguopuuuf'))
结果为
runfile('C:/Users/DELL/Desktop/python/duplicate.py', wdir='C:/Users/DELL/Desktop/python')
[2, 6, 3]
{'a': 3, 'u': 4}
public class Solution {
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;
// Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++
// 这里要特别注意~返回任意重复的一个,赋值duplication[0]
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
public boolean duplicate(int numbers[],int length,int [] duplication) {
int hash[]=new int[length];
for(int i=0;i<length;i++){
if(hash[numbers[i]]==0){
hash[numbers[i]]++;
}
else{
duplication[0]=numbers[i];
return true;
}
}
return false;
}
}