提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
哈希表中关键码就是数组的索引下标,然后通过下标直接访问数组中的元
一、力扣面试题 02.07. 链表相交
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode L1, L2, HA = new ListNode(-1,headA), HB = new ListNode(-1,headB);
ListNode p1 = HA, p2 = HB;
int lenA = 0, lenB = 0, margin = 0;
while(p1.next != null){
lenA ++;
p1 = p1.next;
}
while(p2.next != null){
lenB ++;
p2 = p2.next;
}
if(lenA > lenB){
L1 = HA;
L2 = HB;
margin = lenA - lenB;
}else{
L1 = HB;
L2 = HA;
margin = lenB - lenA;
}
while(margin > 0){
margin --;
L1 = L1.next;
}
while(L1 != null && L2 != null){
if(L1 == L2){
return L1;
}
L1 = L1.next;
L2 = L2.next;
}
return null;
}
}
二、力扣142. 环形链表 II
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null || head.next == null){
return null;
}
ListNode L = new ListNode(-1,head);
ListNode fast = L.next.next, slow = L.next;
while(fast != null){
if(fast == slow){
ListNode p = L;
while(slow != p){
slow = slow.next;
p = p.next;
}
return p;
}else{
if(fast.next == null || fast.next.next == null){
return null;
}
fast = fast.next.next;
slow = slow.next;
}
}
return null;
}
}
三、力扣242. 有效的字母异位词
class Solution {
public boolean isAnagram(String s, String t) {
int[] flagA = new int[27];
int[] flagB = new int[27];
for(char c : s.toCharArray()){
flagA[c-'a'] += 1;
}
for(char c : t.toCharArray()){
flagB[c - 'a'] += 1;
}
for(int i = 0; i < 27; i ++){
if(flagA[i] != flagB[i]){
return false;
}
}
return true;
}
}
四、力扣9. 字母异位词分组
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new ArrayList<>();
Map<String,List<String>> map = new HashMap<>();
for(String s : strs){
String t = fun(s);
if(!map.containsKey(t)){
map.put(t,new ArrayList<>());
}
List<String> li = map.get(t);
li.add(s);
map.put(t,li);
}
res.addAll(map.values());
return res;
}
public String fun(String s){
String res = "";
int[] arr = new int[27];
for(char c : s.toCharArray()){
arr[c-'a'] += 1;
}
for(int i = 0; i< 26; i ++){
if(arr[i] != 0){
char c =(char) ('a' + i);
res += c;
res += arr[i];
}
}
return res;
}
}
五、力扣9. 字母异位词分组
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new ArrayList<>();
Map<String,List<String>> map = new HashMap<>();
for(String s : strs){
StringBuilder sb = new StringBuilder();
int[] arr = new int[26];
for(char c : s.toCharArray()){
arr[c-'a'] ++;
}
for(int i = 0; i < 26; i ++){
if(arr[i] != 0){
sb.append('a'+i).append(arr[i]);
}
}
String t = sb.toString();
map.put(t,map.getOrDefault(t,new ArrayList<>()));
map.get(t).add(s);
}
res.addAll(map.values());
return res;
}
}