999. 车的可用捕获量
class Solution {
public int numRookCaptures(char[][] board) {
// 定义上下左右四个方向
int[] dx = {-1, 1, 0, 0};
int[] dy = {0, 0, -1, 1};
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
// 找到白车所在的位置
if (board[i][j] == 'R') {
// 分别判断白车的上、下、左、右四个方向
int res = 0;
for (int k = 0; k < 4; k++) {
int x = i, y = j;
while (true) {
x += dx[k];
y += dy[k];
if (x < 0 || x >= 8 || y < 0 || y >= 8 || board[x][y] == 'B') {
break;
}
if (board[x][y] == 'p') {
res++;
break;
}
}
}
return res;
}
}
}
return 0;
}
}
面试题63. 股票的最大利润
class Solution {
public int maxProfit(int[] prices) {
if(prices.length<2){
return 0;
}
int min = prices[0];
int max = prices[1]-min;
for(int i = 1;i<prices.length-1;i++){
min = Math.min(min,prices[i]);
max = Math.max(max,prices[i+1]-min);
}
return max<0?0:max;
}
}
class Solution {
public int maxProfit(int[] prices) {
if(prices.length==0) return 0;
int ans=0,min=prices[0],n=prices.length;
for(int i=0;i<n;i++){
if(prices[i]<=min) min=prices[i];
else
ans=Math.max(ans,prices[i]-min);
}
return ans;
}
}
面试题18. 删除链表的节点
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if(head.val == val) return head.next;
ListNode pre = head, cur = head.next;
while(cur != null && cur.val != val) {
pre = cur;
cur = cur.next;
}
pre.next = cur.next;
return head;
}
}
class Solution {
public ListNode deleteNode(ListNode head, int val) {
ListNode dummyHead = new ListNode(0), pre = dummyHead;
dummyHead.next = head;
while(pre.next != null) {
if(pre.next.val == val) {
pre.next = pre.next.next;
break;
}
pre = pre.next;
}
return dummyHead.next;
}
}
你知道的越多,你不知道的越多。
有道无术,术尚可求,有术无道,止于术。
如有其它问题,欢迎大家留言,我们一起讨论,一起学习,一起进步