编程练习
题目:在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
思路:感觉这道题出的没什么意义,你需要返回一个随机的重复数字,那我返回第一个出现的重复数也能通过。找到数组中第一个重复的数字的题之前做过,两层嵌套for循环即可,注意题目中设置的返回值得条件和函数参数即可。
java代码如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43import java.util.ArrayList;
public class Duplicate {
/**
*
* @param numbers 输入数组
* @param length 输入数组长度
* @param duplication 输出数组,只包含一个元素
* @return
*/
public static boolean duplicate(int numbers[],int length,int [] duplication) {
//设置返回标志
boolean flag=false;
//用来装选中的重复数字的容器
ArrayList<Integer> list=new ArrayList<Integer>();
for(int i=0;i<length;i++) {
int count=0; //统计比较中出现数字相同的次数
for(int j=0;j<length;j++) {
if(numbers[i]==numbers[j]) {
count++;
}
}
//因为这个for循环的两层都是从0开始的,所以每一次都会遇到和自己比较,所以count至少为1,只有大于1时才说明有重复的数
if(count>=2) {
list.add(numbers[i]);
flag=true;
}
}
//如果没有重复元素,返回false,且令duplication[0]=-1
if(list.size()==0) {
duplication[0]=-1;
return false;
}
duplication[0]=list.get(0);
return flag;
}
public static void main(String[] args) {
int arr[]= {2,1,3,0,4};
int dup[]=new int[1];
System.out.println(duplicate(arr,arr.length,dup));
System.out.println(dup[0]);
}
}