数组中重复的数字问题
2016-04-23 17:02
239 查看
如题所述,这类问题出现的频率太高了,有必要进行归纳归纳~
--->给定一个长度为N的数组,其中每个元素的取值范围都是1到N。判断数组中是否有重复的数字。(原数组不必保留)
方法1.
对数组进行排序(快速,堆),然后比较相邻的元素是否相同。
时间复杂度为O(nlogn),空间复杂度为O(1)。
方法2.
使用bitmap方法。
定义长度为N/8的char数组,每个bit表示对应数字是否出现过。遍历数组,使用 bitmap对数字是否出现进行统计。
时间复杂度为O(n),空间复杂度为O(n)。
方法3.
遍历数组,假设第 i 个位置的数字为 j ,则通过交换将 j 换到下标为 j 的位置上。直到所有数字都出现在自己对应的下标处,或发生了冲突。
时间复杂度为O(n),空间复杂度为O(1)。
示例代码:
剑指offer练习题
--->给定一个长度为N的数组,其中每个元素的取值范围都是1到N。判断数组中是否有重复的数字。(原数组不必保留)
方法1.
对数组进行排序(快速,堆),然后比较相邻的元素是否相同。
时间复杂度为O(nlogn),空间复杂度为O(1)。
方法2.
使用bitmap方法。
定义长度为N/8的char数组,每个bit表示对应数字是否出现过。遍历数组,使用 bitmap对数字是否出现进行统计。
时间复杂度为O(n),空间复杂度为O(n)。
方法3.
遍历数组,假设第 i 个位置的数字为 j ,则通过交换将 j 换到下标为 j 的位置上。直到所有数字都出现在自己对应的下标处,或发生了冲突。
时间复杂度为O(n),空间复杂度为O(1)。
示例代码:
剑指offer练习题
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) { //思路:遍历数组,假设第 i 个位置的数字为 j ,则通过交换将 j 换到下标为 j 的位置上。 //直到所有数字都出现在自己对应的下标处,或发生了冲突。 //ps:由于长度为n的数组里的所有数字都在0到n-1的范围内,所以不需要扩展额外的空间 for(int i=0;i<length;i++){ if(numbers[i]!=i){ if(numbers[i]!=numbers[numbers[i]]) swap(numbers[i],numbers[numbers[i]]); else{ *duplication=numbers[i]; return true; } } } return false; } };
相关文章推荐
- hdu 5672 String【尺取法】
- JavaIO流分类详解与常用流用法实例
- 使用ab对nginx进行压力测试
- 朴素贝叶斯
- 读取properties配置文件
- 【GDOI2016模拟4.22】总结
- 二分查找,递归和非递归
- PL/SQL存储过程调试
- Android Touch事件传递机制通俗讲解
- 保留两位小数
- 如何在Windows系统安装pygame
- MAC下双开UNITY
- The 13th Zhejiang Provincial Collegiate Programming Contest - I
- hibernate---一级缓存, 二级缓存, 查询缓存
- CodeForces - 404A(模拟题)
- 2016年4月21日百度笔试题--FirstInOutPage
- start_armboot函数简介
- HTML网页模版/DTD有三种类型
- 编码惯例
- 网络制式(Duplex Mode)