【剑指offer】50.数组中重复的数字

题目

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。


分析

这道题是比较基础,主要思路如下:

  1. 首先判断数组是否为空,若为空直接返回false;
  2. 然后初始化集合及其对应哈希表,利用哈希表统计每个元素出现的次数;
  3. 之后遍历整个集合,获取第一个出现次数大于1的元素,并将其加入重复数组,最终返回true,若无则直接返回false;

github链接:JZ50-数组中重复的数字


C++代码

#include <iostream>
#include <map>
#include <set>
#include <cstring>
using namespace std;

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) {
	        // 判断数组是否为空 
			if(numbers == NULL || length <= 0){
	        	return false;
			}
			 
			map<int,int> number_hash;
			set<int> number_set;
			for(int i = 0 ; i < length ; i++){
				number_hash[numbers[i]]++;
				number_set.insert(numbers[i]);
			}
			
			int cnt = 0;
			set<int>::iterator it;
			for(it = number_set.begin() ; it != number_set.end() ; it++){
				if(number_hash[*it] > 1){
					duplication[cnt++] = *it;
					return true;
				}
			}
			return false;
	    }
};

int main()
{
	int n;
	Solution s;
	while(cin>>n){
		int* array = new int[n];
		int* duplication = new int[n];
		memset(array,0,sizeof(int)*n);
		memset(duplication,0,sizeof(int)*n);
		for(int i = 0; i < n ; i++){
			cin>>array[i];
		}
		bool flag = s.duplicate(array,n,duplication);
		if(flag){
			for(int i = 0 ; i < n ; i++){
				cout<<duplication[i]<<" ";
			}
			cout<<endl;
		}
	}
	
	
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

daipuweiai

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值