判断数组中相同元素个数大于1个的方法
流程图
flowchart TD
Start(开始)
Input(输入数组)
Count(计数器初始化为0)
ForLoop(遍历数组)
Compare(比较元素)
If(判断是否相等)
Increment(计数器加1)
End(结束)
Start-->Input
Input-->Count
Count-->ForLoop
ForLoop-->Compare
Compare-->If
If(no)-->ForLoop
If(yes)-->Increment
Increment-->End
步骤
步骤 | 代码 | 说明 |
---|---|---|
1 | int[] array = {1, 2, 3, 3, 4, 5, 5} |
定义一个整型数组,并初始化数组元素。 |
2 | int count = 0 |
初始化一个计数器,用于统计相同元素的个数。 |
3 | for (int i = 0; i < array.length; i++) |
遍历数组。 |
4 | for (int j = i + 1; j < array.length; j++) |
在遍历时,比较当前元素和后面的元素是否相等。 |
5 | if (array[i] == array[j]) |
判断两个元素是否相等。 |
6 | count++ |
如果相等,则计数器加1。 |
7 | if (count > 1) |
判断计数器是否大于1,即数组中相同元素的个数是否大于1。 |
8 | System.out.println("数组中存在相同元素"); |
输出结果:数组中存在相同元素。 |
9 | else |
如果计数器小于等于1。 |
10 | System.out.println("数组中不存在相同元素"); |
输出结果:数组中不存在相同元素。 |
代码实现
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3, 3, 4, 5, 5};
int count = 0;
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] == array[j]) {
count++;
}
}
}
if (count > 1) {
System.out.println("数组中存在相同元素");
} else {
System.out.println("数组中不存在相同元素");
}
}
}
这段代码的作用是判断数组中是否存在相同的元素。首先,我们定义一个整型数组,并初始化数组元素。然后,我们初始化一个计数器,用于统计相同元素的个数。接下来,我们使用嵌套循环遍历数组,比较当前元素和后面的元素是否相等,如果相等,则计数器加1。最后,我们判断计数器是否大于1,如果大于1,则输出结果:数组中存在相同元素;否则,输出结果:数组中不存在相同元素。
测试代码
我们可以使用不同的测试用例来验证这段代码的正确性。
public class Main {
public static void main(String[] args) {
int[] array1 = {1, 2, 3, 3, 4, 5, 5};
int[] array2 = {1, 2, 3, 4, 5, 6, 7};
System.out.println("数组1中的相同元素个数大于1个吗?");
checkDuplicate(array1);
System.out.println("数组2中的相同元素个数大于1个吗?");
checkDuplicate(array2);
}
public static void checkDuplicate(int[] array) {
int count = 0;
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] == array[j]) {
count++;
}
}
}
if (count > 1) {
System.out.println("存在相同元素");
} else {
System.out.println("不存在相同元素");
}
}
}
执行以上测试代码,我们可以得到以下输出结果:
数组1中的相同元素个数大于1个吗?
存在相同元素
数组2中的相同元素个数大于1个吗?
不存在相同元素