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

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;

      }

    }

相关推荐
6Hzlia26 分钟前
【Hot 100 刷题计划】 LeetCode 48. 旋转图像 | C++ 矩阵变换题解
c++·leetcode·矩阵
Morwit2 小时前
【力扣hot100】 1. 两数之和
数据结构·c++·算法·leetcode·职场和发展
py有趣2 小时前
力扣热门100题之岛屿的数量(DFS/BFS经典题)
leetcode·深度优先·宽度优先
qinian_ztc4 小时前
frida 14.2.18 安装报错解决
算法·leetcode·职场和发展
田梓燊5 小时前
2026/4/11 leetcode 3741
数据结构·算法·leetcode
小肝一下7 小时前
每日两道力扣,day8
c++·算法·leetcode·哈希算法·hot100
star learning white8 小时前
线性代数1
线性代数
语戚9 小时前
力扣 51. N 皇后:基础回溯、布尔数组优化、位运算全解(Java 实现)
java·算法·leetcode·力扣·剪枝·回溯·位运算
py有趣9 小时前
力扣热门100题之螺旋矩阵
算法·leetcode
人道领域9 小时前
【LeetCode刷题日记】383 赎金信
算法·leetcode·职场和发展