# -*- coding: utf-8 -*-
n = 1
input_list = []
while True:
inputChar = input('输入数组第' + str(n) + '个元素,直接回车结束输入\n')
if inputChar == '':
break
input_list.append(inputChar)
n += 1
print(input_list)
countDict = {}
for item in input_list:
if item in countDict:
countDict += 1
else:
countDict = 1
maxCount = max(countDict.values())
for key, value in countDict.items():
if value == maxCount:
print("出现最多的元素是:", key, ",出现次数为", value)
countDict.pop(key)
break
maxCount = max(countDict.values())
for key, value in countDict.items():
if value == maxCount:
print("出现第二多的元素是:", key, ",出现次数为", value)
countDict.pop(key)
break
然而最简单的方法是from collections import Counter
多熟悉下标准库的容器
遍历数组放进dict里,如果key不存在就赋值1,存在累加1
遍历完后给值做个排序,取后两个就完事了 哈希表,请 本帖最后由 ustc 于 2020-9-4 00:40 编辑
lz知道hashmap吗?在python里好像是dict?这种真算easy的了,不过这题不严谨,重复次数有3个即以上相同没说怎么处理,那我也不管了
class Solution {
public List<Integer>find123(int[] a) {
//没说怎么处理,那就直接返回null了
if (a == null || a.length < 3) {return null;}
int max = 0; int secondMax = 0;
Map<Integer, Integer> map = new HashMap<>();
List<Integer> ans = new ArrayList<>();
for (int i: a) {
int count = 0;
if (map.containsKey(i)) {
count = 1+map.get(i);
} else {
count = 1;
}
map.put(i, count);
if (count > max) { secondMax = max; max = count;}
else if (count == max) {secondMax = max;}
else if (count < max && count > secondMax) {secondMax =count;}
}
for (Map.Entry<Integer, Integer> entry: map.entrySet()) {
if (entry.getValue() == max || entry.getValue() == secondMax) {
ans.add(entry.getKey());
}
}
return ans;
}
} 本帖最后由 hein 于 2020-9-5 10:02 编辑
为什么不用正则呢
页:
[1]