1-1000这1000个数放在含有1001个元素的数组中,只有唯一的一个元素值重复,其他均只出现一次。每个数组元素只能访问一次,设计一个算法,将它找出来;不用辅助存储空间,能否设计一个算法实现?
思路:
1.使用到了异或:A^A=0 B^0=B
2.将数组中的数异或,再与1-1000这1000个数异或,最后得到的结果即是重复的数
例:A^B^C^D^E^F^B^A^B^C^D^E^F=(A^A)^(B^B)^(C^C)^(D^D)^(E^E)^(F^F)^B=0^B=B
使用小数据测试:
import java.util.*;
public class weicaozuoapp {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int[] test=new int[11];
for(int i=0;i<test.length;i++) {
test[i]=sc.nextInt();
}
//先得到1-10的异或
int temp=0;
for(int i=1;i<test.length;i++) {
temp=temp^i;
}
for(int i=0;i<test.length;i++) {
temp=temp^test[i];
}
System.out.print("重复的元素为:"+temp);
}
}
暴力破解法:
import java.util.*;
public class weicaozuoapp {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int[] test=new int[11];
for(int i=0;i<test.length;i++) {
test[i]=sc.nextInt();
}
//设置一个长度为10的数组
//test数组中1-10的数据分别对应temp数组的下标
//若出现一个数据则将该位置数据加一
int[] temp=new int[10];
for(int i=0;i<test.length;i++) {
temp[test[i]-1]=temp[test[i]-1]+1;
}
for(int i=0;i<temp.length;i++) {
if(temp[i]==2) {
int t=i+1;
System.out.print("重复的元素为:"+t);
break;
}
}
}
}
练习1:一个数组里除了某一个数字外,其他的数字都出现了两次,请写程序找出只出现一次的数字。
import java.util.*;
public class weicaozuoapp {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int[] test=new int[11];
for(int i=0;i<test.length;i++) {
test[i]=sc.nextInt();
}
int temp=0;
for(int i=0;i<test.length;i++) {
temp=temp^test[i];
}
System.out.print("落单的元素为:"+temp);
}
}
练习2:请实现一个函数,输入一个整数,输出该数二进制表示中1的个数
例:9的二进制为1001,有两个1
import java.util.*;
public class weicaozuoapp {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int test=sc.nextInt();
int count=0;
for(int i=0;i<32;i++) {
//将1不断左移,与该数与运算,结果与1左移到该位的值相同,则该位为1
if((test&(1<<i))==(1<<i)) {
count++;
}
}
System.out.print("含有1的个数为:"+count);
}
}