环形链表
问题:
代码实现:
public class Solution {
public boolean hasCycle(ListNode head {
Set<ListNode> set = new HashSet<>(;
while (head != null{
if (set.contains(head
return true;
set.add(head;
head = head.next;
}
return false;
}
}
相交链表
力扣160题
代码实现:
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB {
Set<ListNode> set = new HashSet<>(;
ListNode temp = headA;//头指针不方便移动,赋值给temp
while (temp != null{
set.add(temp;
temp = temp.next;
}
temp = headB;
while (temp != null{
if (set.contains(temp//如果保护这个节点,则直接返回这个节点。
return temp;
temp = temp.next;
}
return null;
}
}
多数元素
力扣169题
代码实现:
class Solution {
public int majorityElement(int[] nums {
Map<Integer, Integer> map = new HashMap<>(;
//把数组中的每个数字和对应出现的次数存放到map中
for(Integer i : nums{
Integer count = map.get(i;
count = count == null ? 1 : ++count;
map.put(i,count;
}
//把数组中
for(Integer i : map.keySet({
Integer count = map.get(i;
if (count > nums.length / 2
return i;
}
return 0;
}
}