链表
目录
第四天没做,第五天也没做,今天上午挑选了两道第四天的题
面试题链表相交
似懂非懂,比较的确实不是单纯的一个值相等,而是除了值相等外,好像是地址还要相等..
ListNode类是力扣题目给你提供的自定义的节点类,LinkedList是java原生的双向链表类,节点类Node存在于内部,从外部访问不到。
复制来源[java中有ListNode吗?ListNode与LinkedList的区别是什么呢?-Java-CSDN问答]
正解:
public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { //使用while循环求出链表长度 int aLength=0,bLength=0; ListNode curA=headA,curB=headB; while(curA!=null){ aLength++; curA=curA.next; } while(curB!=null){ bLength++; curB=curB.next; } //让两个链表的结束位置相同 //first--起点位置设置 curA=headA; curB=headB; //制定统一标准:让aLength作为最长的链表,curA指向最长链表头节点 if(bLength>aLength){ int ltmp=bLength; bLength=aLength; aLength=ltmp; ListNode ctmp=curB; curB=curA; curA=ctmp; } //求长度差值,然后让长的链表的指针移动到和短的链表一样的起始位置,然后才开始比较指针相等于否 int gap=aLength-bLength; while(gap-- >0){ curA=curA.next; } while(curA!=null){ if(curA==curB) {return curA;} curA=curA.next; curB=curB.next; } return null; } }
24.两两交换链表中的节点
这个是按照c++代码的解题过程写的,关于使用递归解题,我没有搞明白....
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode swapPairs(ListNode head) { //建立虚拟头节点 ListNode dummyNode=new ListNode(-1); dummyNode.next=head; //建立一个指针,继承dummyNode的值,进行位移操作. ListNode cur=dummyNode; while(cur.next!=null && cur.next.next!=null){ //建立中转站节点,实现节点交换操作 ListNode tmp1,tmp2; tmp1=cur.next;// tmp2=cur.next.next.next;// //实现交换操作 //这一步,第一次交换时,正数的第二个值被放在了虚拟的头结点的后继节点 cur.next=cur.next.next; //把放在中转站的节点拿出来赋给实现了第一步交换的节点的后继节点上 cur.next.next=tmp1; //这个时候cur.next.next.next不是未交换时的正数第三个节点,而是已经交换了的第二个节点的后继节点 cur.next.next.next=tmp2; //做完了一轮交换,就移动到后面去 cur=cur.next.next; } return dummyNode.next; } }
哈希表
242.有效的字母异未词
正解:
class Solution { public boolean isAnagram(String s, String t) { //利用辅助数组来记录两个字符串字母出现次数是否相同 //首先去记录字符串s的字母出现次数,利用ASCII的a,差值作为辅助数组的下标,得到了就在该位置自增 //然后记录字符串t的字母出现次数,同理可得,自减操作,当数组元素全为零,就得到了有效的字母异位,输出true int[] record=new int[26]; 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; } }
349.两个数组的交集
正解:
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> tmp=new HashSet<>(); Set<Integer> res=new HashSet<>(); for(int i:nums1) { tmp.add(i); } //这个循环里面判断是否有相同元素 for(int i:nums2){ if(tmp.contains(i)){ res.add(i); } } return res.stream().mapToInt(x -> x).toArray(); } }
202.快乐数
正解:
class Solution { //取出每个数字的位数,进行平方和,放入结果中 int getNextNumber(int n){ int sum=0,cur; while(n>0){ cur=n%10; sum+=cur*cur; n=n/10; } return sum; } public boolean isHappy(int n) { Set<Integer> record=new HashSet<>(); record.add(n); while(n!=1){ n=getNextNumber(n); if(!record.add(n)){ return false; } }return true; } }