HashMap | HashSet |
---|---|
实现了Map接口 | 实现了Set接口 |
存储键值对 | 仅存储对象 |
调用put()方法向map中添加元素 | 调add()方法向set中添加元素 |
HashMap使用键(Key)计算Hashcode | HashSet使用成员对象计算Hashcode值 |
之后再次遇到再补充细节
1 . 找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。
数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
限制:2 <= n <= 100000
class Solution{
public int findRepeatNumber(int[] nums){
Set<Integer> set = new HashSet<>();
for(int i : nums){
if(set.contains(i)){
return i;
}else{
set.add(i);
}
}
return -1;
}
}
注:
出现InputMismatchException异常是输入不匹配,即输入的值数据类型与设置的值数据类型不匹配。
ArrayIndexOutOfBoundsException异常:超出界限异常,即越界。
//或者这种方法
class Solution {
public int findRepeatNumber(int[] nums) {
int[] arr = new int[nums.length];
for(int i = 0; i < nums.length; i++){
arr[nums[i]]++;
if(arr[nums[i]] > 1)
return nums[i];
}
return -1;
}
}
2 . 两个链表的第一个公共节点
输入两个链表,找出它们的第一个公共节点。
我走过你走过的路,你走过我走过的路,我们就相遇了。
这大概就是程序员的浪漫~
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> set = new HashSet<ListNode>();
ListNode tmp = headA;
while(tmp != null){
set.add(tmp);
tmp = tmp.next;
}
tmp = headB;
while(tmp != null){
if(set.contains(tmp)){
return tmp;
}
tmp = tmp.next;
}
return null;
}
}
//或者这种办法
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode A = headA, B = headB;
while(A != B){
A = A != null ? A.next : headB;
B = B != null ? B.next : headA;
}
return B;
}
}