public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode curA = headA;
ListNode curB = headB;
int lenA = 0;
int lenB = 0;
//计算长度;
while(curA != null){
lenA++;
curA = curA.next;
}
while(curB != null){
lenB++;
curB = curB.next;
}
curA = headA;
curB = headB;
//另lenA长度最长;如果lenA长度小,交换;
if(lenA < lenB){
ListNode tempcur = curA;
curA = curB;
curB = tempcur;
int tempLen = lenA;
lenA = lenB;
lenB = tempLen;
}
//A和B末尾对齐
int gap = lenA - lenB;
while(gap-- > 0){
curA = curA.next;
}
while(curA != curB){
curA = curA.next;
curB = curB.next;
}
return curA;
}
}
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
//判断是否相遇
while(fast != null && fast.next != null ){
slow = slow.next;
fast = fast.next.next;
if (slow == fast){
ListNode index1 = fast;
ListNode index2 = head;
while(index1 != index2){
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}
class Solution {
public boolean isAnagram(String s, String t) {
int[] record = new int[26];
// length() 方法用于返回字符串的长度;length:类的属性->数组.length
for(int i = 0; i < s.length() ;i++){
record[s.charAt(i) - 'a']++;
}
for(int i = 0; i < t.length() ;i++){
record[t.charAt(i) - 'a']--;
}
for(int count: record){
if (count != 0){
return false;
}
}
return true;
}
}
import java.util.HashSet;
import java.util.Set;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length ==0 ||nums2 == null || nums2.length ==0){
return new int[0];
}
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
//遍历数组1
for(int i : nums1){
set1.add(i);
}
for(int i : nums2){
if (set1.contains(i)){
set2.add(i);
}
}
//集合转为数组
return set2.stream().mapToInt(x -> x).toArray();
}
}