java语言判断一个列表是否存在重复

本文讨论了如何在循环链表中检测是否存在两个节点相遇的情况,通过使用双指针技巧来实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
假如存在重复,一个节点最终会追上另外的一个节点
*/
public class T1 {


public static void main(String[] args) {

Node f1 = new Node();
Node f2 = f1;
f1.next = null;
f1.value=0;
for(int i =0;i < 20;i ++){

Node f3 = new Node();
f3.value = i;
f1.next = f3;
f1 = f3;

}

System.out.println("是否存在循环:"+ check(f2));
}


static boolean check(Node node){

if(node == null){

return false;
}


Node f1 = node,f2 = node;

while(f1!=null && f2 !=null){

f2 = f2.next;
if(f2!=null&&f2.next!=null && f1.next!=null){
f1 = f1.next;
f2 =f2.next;
if(f1.value == f2.value){

return true;
}else{

System.out.println("!=");
}

}else{

return false;
}

}

return false;
}

static class Node{

public int value;
public Node next;

}

}
可以使用以下步骤来判断两个文件的内容重复率: 1. 读取文件内容并存储为字符串。 2. 将字符串转换为字符数组。 3. 对字符数组进行哈希计算,生成一个唯一的哈希值。 4. 将哈希值保存到一个集合中。 5. 重复以上步骤,直到读取完整个文件。 6. 统计集合中不同哈希值的数量,即为文件的不同哈希值数量。 7. 计算不同哈希值数量与总哈希值数量的比例,即为文件的内容重复率。 下面是一个简单的 Java 代码示例,用于计算两个文件的内容重复率: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashSet; public class FileCompare { public static void main(String[] args) throws IOException { String file1 = "file1.txt"; String file2 = "file2.txt"; double similarity = compareFiles(file1, file2); System.out.println("The similarity between " + file1 + " and " + file2 + " is " + similarity + "%"); } public static double compareFiles(String file1, String file2) throws IOException { HashSet<Integer> hashSet1 = new HashSet<>(); HashSet<Integer> hashSet2 = new HashSet<>(); FileInputStream inputStream1 = new FileInputStream(new File(file1)); FileInputStream inputStream2 = new FileInputStream(new File(file2)); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = inputStream1.read(buffer)) != -1) { String content = new String(buffer, 0, bytesRead); char[] charArray = content.toCharArray(); for (char c : charArray) { hashSet1.add((int) c); } } while ((bytesRead = inputStream2.read(buffer)) != -1) { String content = new String(buffer, 0, bytesRead); char[] charArray = content.toCharArray(); for (char c : charArray) { hashSet2.add((int) c); } } inputStream1.close(); inputStream2.close(); HashSet<Integer> union = new HashSet<>(hashSet1); union.addAll(hashSet2); HashSet<Integer> intersection = new HashSet<>(hashSet1); intersection.retainAll(hashSet2); double similarity = (double) intersection.size() / (double) union.size() * 100; return similarity; } } ``` 在上面的代码中,我们首先定义了两个文件的名称,然后调用 `compareFiles` 方法来计算两个文件的内容重复率。在 `compareFiles` 方法中,我们使用哈希集合来保存文件的哈希值,并计算不同哈希值的数量以及总哈希值的数量来计算文件的内容重复率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值