gpt4 book ai didi

java - 如何避免冒泡排序算法中重复的字符串值?

转载 作者:行者123 更新时间:2023-12-02 08:52:04 25 4
gpt4 key购买 nike

我正在尝试找出如何在排序算法中避免打印重复名称

我忽略空字符串的原因是我正在实现的系统是一个票务预订系统,它仅显示姓名列表而不是空位置。

有人可以帮我吗?

String[] name={"fiona","vacant","allen","fiona","david","vacant","vacant"};
for (int i = 0; i <= (name.length-1); i++){
for (int j = i+1; j < name.length; j++ ){
if (name[i].compareTo(name[j])>0) {
String temp = name[i];
name[i] = name[j];
name[j] = temp;
}
}
if (!name[i].equals("vacant")) {
System.out.println(name[i] + " ");
}
}

最佳答案

只需检查您正在打印的名称是否与前一个相同:

String[] name={"fiona","vacant","allen","fiona","david","vacant","vacant"};
for (int i = 0; i <= (name.length-1); i++){
for (int j = i+1; j < name.length; j++ ){
if (name[i].compareTo(name[j])>0) {
String temp = name[i];
name[i] = name[j];
name[j] = temp;
}
}
if (!name[i].equals("vacant") && (i == 0 || !name[i-1].equals(name[i]))) {
System.out.println(name[i] + " ");
}
}

关于java - 如何避免冒泡排序算法中重复的字符串值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60710471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com