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

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;

      }

    }

相关推荐
csdn_aspnet11 小时前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展
m0_6294947314 小时前
LeetCode 热题 100-----26.环形链表 II
数据结构·算法·leetcode·链表
AI科技星14 小时前
哥德巴赫猜想1+1基于平行素数对等腰梯形网格拓扑与素数渐近密度的大偶数满填充完备性证明
人工智能·线性代数·架构·概率论·学习方法
小羊在睡觉19 小时前
力扣239. 滑动窗口最大值
数据结构·后端·算法·leetcode·go
大大杰哥19 小时前
leetcode hot100(4)矩阵
算法·leetcode·矩阵
叶小鸡20 小时前
小鸡玩算法-力扣HOT100-动态规划(上)
算法·leetcode·动态规划
2601_9577867720 小时前
多平台矩阵系统的反脆弱架构:如何用技术解耦对抗平台规则的不确定性
人工智能·矩阵·架构·平台解耦
凌波粒20 小时前
LeetCode--513.找树左下角的值(二叉树)
java·算法·leetcode
2601_9577875821 小时前
智能矩阵运营系统的流量博弈论:当1000个账号争夺有限流量时,最优调度策略是什么?
人工智能·矩阵·流量调度·智能矩阵运营系统
一只小逸白1 天前
LeetCode Go 常用函数速查表
linux·leetcode·golang