数组中重复的数字
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。(点我直接练习)
分析
一开始在缺乏知识的情况下,我能想到的做法是两个for循环,从第一个位置和剩余所有的位置进行比较,如果相同即输出,没有则从第二个位置开始和剩余的元素进行比较。在使用C++的时候,正常人的做法应为新建一个足够大的数组,默认所有位置的数值为0,之后根据输入的数组每一位的值对应到新建数组的位置上,对应一次则将新数组上该位置加1;很明显,一旦新数组的数值大于1,那么对应于原数组则为重复的数字。而在python上,则使用Counter直接统计就完事,emmm,这又是一道python真香题。
使用到的知识点
C++
哈希建立。
Python
collections包的使用
题解
C++(Clang++ 3.9) : 运行时间:3ms 占用内存:376k
class Solution {
public:
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number
// Return value: true if the input is valid, and there are some duplications in the array // number
// otherwise false
bool duplicate(int numbers[], int length, int* duplication) {
int duplicatable[255] = {0};
for(int i = 0;i<length;i++)
duplicatable[numbers[i]]++;
for(int i = 0;i<length;i++){
if(duplicatable[numbers[i]]>1){
duplication[0] = numbers[i];
return true;
}
}
return false;
}
};
Python 2.7-运行时间:23ms ,占用内存:5684k
# -*- coding:utf-8 -*-
from collections import Counter
class Solution:
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(self, numbers, duplication):
count = Counter(numbers)
for value,time in count.items():
if time>1 :
duplication[0] = value
return True
return False