职业经验 # 每日一道面试题 # 有一个数组 [1,3,8,9,15,12,15,3,3,9],找出相等的数字 15 和 9

金主 for 求职面试圈 · April 14, 2018 · Last by 林月 replied at May 19, 2022 · 2259 hits

注意:

3 3 3 这个是 3 个相等的数字了,这个不算
只能是 2 个数字相等,3 个数字相等不行

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
共收到 14 条回复 时间 点赞
1Floor has deleted

[k for k,v in Counter(testlist).items() if v == 2]

from collections import Counter

source = [1, 3, 8, 9, 15, 12, 15, 3, 3, 9]


# 不使用 python 标准库
def get_2dup(candidates):
    if candidates is None:
        return []
    if len(candidates) <= 1:
        return []
    count_result = {}
    for candidate in candidates:
        count_result[candidate] = count_result.get(candidate, 0) + 1
    return [k for k, v in count_result.items() if v == 2]


# 使用Counter
def get_2dup_counter(candidates):
    if candidates is None:
        return []
    if len(candidates) <= 1:
        return []
    count_result = Counter(candidates)
    return [k for k, v in count_result.items() if v == 2]


if __name__ == '__main__':
    print(get_2dup(source))
    print(get_2dup([1]))
    print(get_2dup([]))
    print(get_2dup(None))
    print(get_2dup_counter(source))
    print(get_2dup_counter(None))
    print(get_2dup_counter([]))
    print(get_2dup_counter([9]))

arr = [1,3,8,9,15,12,15,3,3,9]
d = {}
for i in arr:
    if arr.count(i) == 2:
        d[i] = '重复' + str(arr.count(i)) + '次'
print(d)
FelixKang 回复

感觉字典是个多余的操作……

程明远 回复

没有多余吧,字典 key 是数组里的数值,value 是这个数值的个数。

9Floor has deleted
panda 回复

额,直接 If list.count(i) ==2 之后 print(i) 不就成了吗..

int [] arr = { 1,3,8,9,15,12,15,3,3,9};
        for (int i = 0; i < arr.length; i++) {
            int count = 0;
            for (int j = 0; j < arr.length; j++) {
                if(arr[i] == arr[j] && i != j){
                    count++;
                }
            }

            if(count == 1) {
                System.out.println(arr[i]+" ,");
            }
        }
def func(l):
    d = dict()
    for each in l:
        if each not in d:
            d[each] = 1
        else:
            d[each] += 1
    new = [m for m,n in d.items() if n == 2]
    return new

答案

public static void main(String[] args) {
        int array[]= new int[]{1,3,8,9,15,12,15,3,3,9};

        HashMap<Integer, Integer> map = new HashMap<>();
        for(int i=0;i<array.length;i++){
            if(map.containsKey(array[i])) {
                map.put(array[i], map.get(array[i]) + 1);
            } else {
                map.put(array[i], 1);
            }
        }

        for (HashMap.Entry<Integer, Integer> entry : map.entrySet()) {
            if(entry.getValue() == 2) {
                System.out.println("key:" + entry.getKey() + ", value:" + entry.getValue());
            }
        }

    }

用 Counter

from collections import Counter

[k for k, v in Counter(a).items() if v == 2]

l=[1,3,8,9,15,12,15,3,3,9]
print([i for i in set(l) if l.count(i)==2])

需要 Sign In 后方可回复, 如果你还没有账号请点击这里 Sign Up