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

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;

      }

    }

相关推荐
普贤莲花2 小时前
【2026年第11周---写于20260322】
程序人生·算法·leetcode
小白自救计划2 小时前
力扣知识点杂集
算法·leetcode·哈希算法
承渊政道2 小时前
【优选算法】(实战体验滑动窗口的奇妙之旅)
c语言·c++·笔记·学习·算法·leetcode·visual studio
qq_283720053 小时前
WebGL基础教程(十四):投影矩阵深度解析——正交 vs 透视,从公式推导到实战
线性代数·矩阵·webgl·正交·投影
承渊政道3 小时前
【优选算法】(实战感悟二分查找算法的思想原理)
c++·笔记·学习·算法·leetcode·visual studio code
重生之我是Java开发战士3 小时前
【递归、搜索与回溯】记忆化搜索:斐波那契数列,不同路径,最长递增子序列,猜数字游戏II,矩阵中最长递增路径
算法·leetcode·深度优先
爱吃涮毛肚的肥肥(暂时吃不了版)3 小时前
Leetcode——181.超过经理收入的员工
算法·leetcode·职场和发展
Charlie_lll3 小时前
力扣解题-接雨水
算法·leetcode
We་ct4 小时前
LeetCode 74. 搜索二维矩阵:两种高效解题思路
前端·算法·leetcode·矩阵·typescript·二分查找