数组中重复的数字
题目描述:
解题思路:
思路一:
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(NULL==numbers||length==0) return false; sort(numbers,numbers+length-1); for(int i=0;i<length;i++) { if(numbers[i]==numbers[i+1]) { duplication[0]=numbers[i]; return true; } } return false; } };
思路二:
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(NULL==numbers||length==0) return false; int hashtable[255]={0}; //定义哈希表 for(int i=0;i<length;i++) { hashtable[numbers[i]]++; } for(int i=0;i<length;i++) { if(hashtable[numbers[i]]>1) { duplication[0]=numbers[i]; return true; } } return false; } };
思路三:
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(NULL==numbers||length==0) return false; for(int i=0;i<length;i++) { if(numbers[i]<0||numbers[i]>length) { return false; } } for(int i=0;i<length;i++) { while(numbers[i]!=i) { if(numbers[i]==numbers[numbers[i]]) { duplication[0]=numbers[i]; return true; } int temp=numbers[i]; numbers[i]=numbers[temp]; numbers[temp]=temp; } } return false; } }; //虽然说代码中有两层循环,但是每个数字最多交换两次就能找到属于它自己的位置了,所以说时间复杂度是O(n),空间复杂度是O(1)
在上述的代码总,找到的重复数字通过参数duplication传给函数的调用者,而函数的返回值表示数组中是否有重复的数字,当输入的数组中有重复的数字的话,就会返回true,如果没有重复数字的话,就会返回false
测试用例
本网页所有视频内容由 imoviebox边看边下-网页视频下载, iurlBox网页地址收藏管理器 下载并得到。
ImovieBox网页视频下载器 下载地址: ImovieBox网页视频下载器-最新版本下载
本文章由: imapbox邮箱云存储,邮箱网盘,ImageBox 图片批量下载器,网页图片批量下载专家,网页图片批量下载器,获取到文章图片,imoviebox网页视频批量下载器,下载视频内容,为您提供.
阅读和此文章类似的: 全球云计算