数组中重复的数字

这篇博客探讨了三种找出数组中重复数字的方法:1) 使用快速排序,时间复杂度为O(nlog(n)),空间复杂度为O(1);2) 利用HashMap,时间复杂度为O(n),空间复杂度为O(n);3) 通过排序序列交换,时间复杂度为O(n),空间复杂度为O(1)。每种方法都详细解释了其实现思路和空间时间效率。
1.快排,时间:O(nlog(n)),空间:O(1)
2.用一个HashMap,时间:O(n),空间:O(n)

顺序扫描数组,如果HashMap没有包含当前数字,就把这个数字放入HashMap,否则,就为重复数字。

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) {
        map<int, int>M;
        for (int i = 0; i < length; i++)        
            M[numbers[i]]++;
        for (int i = 0; i < length; i++)
        if (M[numbers[i]] > 1 )
        {
                duplication[0] = numbers[i];
                return true;
        }            
        return false;
    }
};
3. 安排序列交换,时间:O(n),空间:O(1)

顺序扫描数组,判断当前扫描的每个数字是否满足 numbers[i]=i ,如果不满足,则说明这个数字不在对应的位置上,于是把将这个数字与numbers[numbers[i]]交换,如果扫描某个数字的过程中发现numbers[i]=numbers[numbers[i]],则说明numbers[i]在i 位置和numbers[i]位置出现了两次,所以是重复数字。
空间复杂度为什么是O(n):因为顺序遍历一个for循环,循环里面的while和n没关系,交换对于一个数来说最多 两次(一次被动,一次主动[指的是让i==numbers[i]]),

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) {
		for (int i = 0; i<length; i++)
		{
			while (i != numbers[i])
			{
				if (numbers[i] == numbers[numbers[i]])
				{
					duplication[0] = numbers[i];
					return true;
				}
				swap(numbers[i], numbers[numbers[i]]);
			}
		}
		return false;

	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值