1、数组中有多少个重复元素?
1.先排序,再遍历,判断是否有重复的数字。
2.建立hash数组:把扫描的每个数字(如数字m)则其对应hash数组下标的数+1,若同一位置有重复,hash数组上高的数+1。
关键代码:
int[] hash = new int[length];//
for( int i=0; i<length; i++ ){
hash[array[i]]++;
}
假如array[1] = 3;
就将hash数组的hash[3]加一,rugu哦hash表某个位置是2,就代表array数组出现了两次。
问题2、数组中出现次数超过一半的数字?
1、先排序,后判断。
2、目标数 超过数组长度的一半,对数组同时去掉两个不同的数字,到最后剩下的一个数就是该数字。如果剩下两个,那么这两个也是一样的,就是结果),在其基础上把最后剩下的一个数字或者两个回到原来数组中,将数组遍历一遍统计一下数字出现次数进行最终判断。
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int length=array.length;
if(array==null||length<=0){
return 0;
}
if(length==1){
return array[1];
}
int[] tempArray=new int[length];
for(int i=0;i<length;i++){
tempArray[i]=array[i];
}
for(int i=0;i<length;i++){
//后面需要用零来代表抹除数字,所以对0时做特殊处理
if(tempArray[i]==0){
continue;
}
for(int j=i+1;j<length;j++){
if(tempArray[i]!=tempArray[j]&&tempArray[j]!=0){
tempArray[i]=0;//此处用0代表抹去该数字
tempArray[j]=0;
break;
}
}
}
for(int i=0;i<length;i++){
System.out.println(tempArray[i]);
}
//找出未被抹去的数字
int result=0;
for(int i=0;i<length;i++){
if(tempArray[i]!=0){
result=tempArray[i];
break;
}
}
int times=0;
for(int i=0;i<length;i++){
if(result==array[i]){
times++;
}
}
if(times*2<length){
result=0;
}
return result;
}
}`
3、如果一个数出现的次数超过数组一半的长度,那么就是说出现的次数比其他所有数字出现的次数还要多。因此我们可以考虑保存2个值,一个是数组中的一个数,一个是数的次数。当我们遍历到下一个数字的时候,如果下一个数字和我们之前保存的数字相同,则次数加1,如果不同则次数减1。如果次数为0了这保存当前遍历到的数,并把次数设为1。遍历完整个数组之后,返回当前保存的数字,即是我们要找的数字。
int MoreThanHalfNum(int* numbers, int length)
{
int result = numbers[0];
int time = 1 ;
for (int i = 1 ;i < length ; i++)
{
if (0 == time)
{
result = numbers[i] ;
time++ ;
}
else if (numbers[i] == result)
{
time++;
}
else
{
time-- ;
}
}
return result ;
}
int main()
{
int numbers[] = {1,3,3,2,3,2,3,3,2};
cout<<MoreThanHalfNum(numbers, 9);
getchar();
return 0;
}