力扣打卡——搜索二维矩阵、相交链表

240. 搜索二维矩阵 II - 力扣(LeetCode)

思路:

直接从右边开始判断,大于往下走,小于就往左走

复制代码
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int n=matrix.length;
        int m=matrix[0].length;
        //从右上角开始
        int i=0;
        int j=m-1;
        while(i < n && j>=0){
            if(matrix[i][j]==target) return true;
            //往下走
            if(target > matrix[i][j]) {
                i++;   
                //往左走
            }else { 
                 j--;
            }
        }
        return false;
    }
}

160. 相交链表 - 力扣(LeetCode)

思路:

标准的长度差法,完全正确:

  1. 分别计算两个链表的长度

  2. 让长链表的指针先走长度差步

  3. 然后两个指针一起走,相遇点就是交点

    /**

    • 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) {
      if(headA==null || headB ==null){
      return null;
      }
      ListNode nodeA=headA;
      ListNode nodeB=headB;
      int lenA=0,lenB=0;
      while(nodeA!=null){
      nodeA=nodeA.next;
      lenA++;
      }
      while(nodeB!=null){
      nodeB=nodeB.next;
      lenB++;
      }
      //始终认为 a>b
      if(lenB>lenA){
      ListNode tmp=headA;
      headA=headB;
      headB=tmp;
      int lenC=lenA;
      lenA=lenB;
      lenB=lenC;
      }
      int lenC=lenA-lenB;
      while(lenC>0){
      headA=headA.next;
      lenC--;
      }

      复制代码
        while(headA!=null && headB !=null){
           if(headA==headB){
               return headA;
           }
           headA=headA.next;
          headB=headB.next;
        }
        return null;

      }

    }

相关推荐
退休倒计时3 小时前
【每日一题】LeetCode 53. 最大子数组和 TypeScript
数据结构·算法·leetcode·typescript
洛水水5 小时前
【力扣100题】86.柱状图中最大的矩形
算法·leetcode·职场和发展
洛水水7 小时前
【力扣100题】81.寻找两个正序数组的中位数
数据结构·算法·leetcode
洛水水7 小时前
【力扣100题】85.每日温度
算法·leetcode·职场和发展
Kurisu_红莉栖7 小时前
力扣56合并区间
算法·leetcode
开源Z8 小时前
LeetCode 135 · 分发糖果:两次扫描,先左后右取最大
算法·leetcode
退休倒计时8 小时前
【每日一题】LeetCode 19. 删除链表的倒数第 N 个结点 TypeScript
leetcode·链表·typescript
怪兽学LLM11 小时前
LeetCode 21 合并两个有序链表:彻底理解虚拟头节点(Dummy)套路
python·leetcode·链表
_日拱一卒12 小时前
LeetCode:22括号生成
算法·leetcode·职场和发展
洛水水12 小时前
【力扣100题】88.多数元素
数据结构·算法·leetcode