第一题:求最大步数

整数数组nums与整数k,从下标0开始,每次可以从i向后移动到j,满足abs(nums[i]-nums[j])<=k,求最大步数

解法:回溯算法,用path记录下标路径

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
/* Write Code Here */
// 回溯算法 path为路径
maximumSteps(nums, k) {
this.nums = nums;
this.k = k;
this.maxStep = -1;
const path = [0];
this.fn(path);
return this.maxStep;
}

fn(path) {
// 终点加入结果
if (path.at(-1) === this.nums.length - 1) {
this.maxStep = Math.max(this.maxStep, path.length - 1);
// console.log(path)
return;
}

for (let i = path.at(-1) + 1; i < this.nums.length; i++) {
if (Math.abs(this.nums[i] - this.nums[path.at(-1)]) <= this.k) {
path.push(i);
this.fn(path);
path.pop();
}
}
}
}
let res;

let nums_size = readInt();

let nums = new Array();
let nums_item;
for (let nums_i = 0; nums_i < nums_size; nums_i++) {
nums.push(readInt());
}
let k = readInt();
let acmSolution = new Solution();
res = acmSolution.maximumSteps(nums, k);
print(res);

按理说没有什么特殊情况了,但是测试通过只有55%。

第二题:求众数

一个整数数组nums与整数k,数组每个元素nums[i]都可以在[nums[i]-k, nums[i]+k]内进行一次变化,返回数组变化后最大的众数

解法:暴力解法,遍历每个元素,计算整个数组满足Math.abs(nums[i] - nums[j]) <= k的个数,求最大值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
/* Write Code Here */
maximumOccurrences(nums, k) {
let maxnum = 1;
// nums.sort();
for (let i = 0; i < nums.length; i++) {
let curnum = 0;
for (let j = 0; j < nums.length; j++) {
if (Math.abs(nums[i] - nums[j]) <= k) {
curnum++;
}
}
maxnum = Math.max(curnum, maxnum);
}
return maxnum;
}
}
let res;

let nums_size = readInt();

let nums = new Array();
let nums_item;
for (let nums_i = 0; nums_i < nums_size; nums_i++) {
nums.push(readInt());
}
let k = readInt();
let acmSolution = new Solution();
res = acmSolution.maximumOccurrences(nums, k);
print(res);

通过率88%,其他的兴许是超时了。

总结

这次算法题挺简单,都算是力扣中等难度。

虽然牛客是acm模式,但是提前写好了IO处理,好评!