1. 程式人生 > >劍指offer 50. 陣列中重複的數字

劍指offer 50. 陣列中重複的數字

原題

在一個長度為n的數組裡的所有數字都在0到n-1的範圍內。 陣列中某些數字是重複的,但不知道有幾個數字是重複的。也不知道每個數字重複幾次。請找出陣列中任意一個重複的數字。 例如,如果輸入長度為7的陣列{2,3,1,0,2,5,3},那麼對應的輸出是第一個重複的數字2。

Reference Answer

思路分析

直接新建一個dict用於計數數字出現次數,再對dict按照值進行排序,輸出滿足需求的key即可。

# -*- coding:utf-8 -*-
class Solution:
    # 這裡要特別注意~找到任意重複的一個值並賦值到duplication[0]
# 函式返回True/False def duplicate(self, numbers, duplication): # write code here if not numbers: return False temp_dict = {} for x in numbers: if x in temp_dict.keys(): temp_dict[x] += 1 duplication[0] = x return
True else: temp_dict[x] = 1 return False