第二周习题

 

递归复习2题:

1、leetcode 92.反转链表II

public ListNode reverseBetween(ListNode head, int m, int n) {
// 定义一个dummyHead, 方便处理
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;

// 初始化指针
ListNode g = dummyHead;
ListNode p = dummyHead.next;

// 将指针移到相应的位置
for(int step = 0; step < m - 1; step++) {
g = g.next;
p = p.next;
}

// 头插法插入节点
for (int i = 0; i < n - m; i++) {
ListNode removed = p.next;
p.next = p.next.next;

removed.next = g.next;
g.next = removed;
}

return dummyHead.next;
}

2、leetcode 1863. 找出所有子集的异或总和再求和

 

class Solution {
int ans = 0;
public int subsetXORSum(int[] nums) {

calcXOR(nums, 0, 0);
return ans;
}

private void calcXOR(int[] nums, int i, int cur) {
if (i >= nums.length) {
ans += cur;
return;
}
calcXOR(nums, i + 1, cur);
calcXOR(nums, i + 1, cur ^ nums[i]);
}
}

数组3题:

1、leetcode 11. 盛最多水的容器

class Solution {
public int maxArea(int[] height) {
int l = 0;
int r = height.length - 1;
int ans = 0;
while (l < r) {
ans = Math.max(ans,
(r - l) * Math.min(height[l], height[r]));
if (height[l] > height[r]) {
r--;
}else {
l++;
}
}
return ans;
}
}

2、leetcode 88. 合并两个有序数组

class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int index = nums1.length - 1;
--n;
--m;
while (m >= 0 && n >= 0) {
if (nums1[m] < nums2[n]) {
nums1[index--] = nums2[n--];
}else {
nums1[index--] = nums1[m--];
}
}
if (n >= 0) {
while (n >= 0) {
nums1[index--] = nums2[n--];
}
}
}
}

3、leetcode 42. 接雨水

class Solution {
public int trap(int[] height) {
if (height == null || height.length < 3) {
return 0;
}
int l = 1;
int r = height.length - 2;
int lM = height[0];
int rM = height[height.length - 1];
int res = 0;
while (l <= r) {
int h = Math.min(lM, rM);
if (lM < rM) {
if (height[l] < h) {
res += h - height[l];
}

lM = Math.max(height[l], lM);
l++;
}else {
if (height[r] < h) {
res += h - height[r];
}

rM = Math.max(rM, height[r]);
r--;
}
}
return res;
}
}
posted @ 2021-05-30 21:13  shouhugyl  阅读(52)  评论(0)    收藏  举报