一个整型数组里除了两个数字之外,其他的数字都出现了两次。 请写程序找出这两个只出现一次的数字。 你可以假设这两个数字一定存在。 数据范围 数组长度 [1,1000]。 样例 输入:[1,2,3,3,4,4] 输出:[1,2]
public static void main(String[] args) {
int [] arr=new int[]{1,1,3,3,4,4,5,6};
int[] numsAppearOnce = findNumsAppearOnce(arr);
for (int i = 0; i <numsAppearOnce.length ; i++) {
System.out.print(numsAppearOnce[i]+" ");
}
}
public static int[] findNumsAppearOnce(int[] nums) {
if (nums.length==0) return null;
int[] helper=new int[2]; //只有两个数 定义一个空间为2的数组
int a=0; //用于比较下标
int b=0;//用于存放数组的下标
int count=0; //用于计算出现次数
while (a<nums.length){//开始比较
for (int i = 0; i <nums.length ; i++) {
if (nums[a] == nums[i]) {
count++;
}
}
//把数组中只出现一次的两个数字放到helper数组中
if (count==1){
helper[b]=nums[a];
b++;
}
count=0; //count归零重新开始计数
a++;
}
return helper;
}
今天水一下 题目比较简单 思路比较明确(手动滑稽)