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

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;

      }

    }

相关推荐
leoufung8 小时前
LeetCode 149: Max Points on a Line - 解题思路详解
算法·leetcode·职场和发展
样例过了就是过了8 小时前
LeetCode热题100 最长公共子序列
c++·算法·leetcode·动态规划
样例过了就是过了12 小时前
LeetCode热题 不同路径
c++·算法·leetcode·动态规划
有为少年13 小时前
从概率估计到“LLM 训练是有损压缩”
人工智能·线性代数·机器学习·计算机视觉·矩阵
Navigator_Z13 小时前
LeetCode //C - 1031. Maximum Sum of Two Non-Overlapping Subarrays
c语言·算法·leetcode
风落无尘14 小时前
第二章《概率与生存》完整学习资料
人工智能·矩阵·概率论
如何原谅奋力过但无声15 小时前
【灵神高频面试题合集01-03】相向双指针、滑动窗口
数据结构·python·算法·leetcode
leoufung15 小时前
LeetCode 42:接雨水 —— 从“矩形法”到双指针的完整思考过程
java·算法·leetcode
_日拱一卒16 小时前
LeetCode:543二叉树的直径
算法·leetcode·职场和发展
穿条秋裤到处跑16 小时前
每日一道leetcode(2026.04.28):获取单值网格的最小操作数
算法·leetcode·职场和发展