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)
思路:
标准的长度差法,完全正确:
-
分别计算两个链表的长度
-
让长链表的指针先走长度差步
-
然后两个指针一起走,相遇点就是交点
/**
-
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;}
}
-