5432. 去掉最低工资和最高工资后的工资平均值
遍历数组,求出最大值和最小值,用(sum(数组之和)- max - min)/ 数组的长度-2
代码
class Solution {
public double average(int[] salary) {
double sum = 0;
double max = salary[0];
double min = salary[0];
for (int i = 0; i < salary.length; i++) {
if (max < salary[i]) {
max = salary[i];
}
if (min > salary[i]) {
min = salary[i];
}
sum = sum + salary[i];
}
double ave = (sum - max - min) / (salary.length - 2);
return ave;
}
}
5433. n 的第 k 个因子
直接暴力循环,将(n%i==0)的值存入数组中,最后用数组的长度和K来进行判断
代码
class Solution {
public int kthFactor(int n, int k) {
int[] array = new int[n];
int num = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
array[num++] = i;
}
}
if (num < k) {
return -1;
} else {
return array[k - 1];
}
}
}
5434. 删掉一个元素以后全为 1 的最长子数组
正顺序遍历一遍数组,求出每个元素前面有多少个1
倒顺序遍历一遍数组,求出每个元素后面有多少个1
用Math,max()函数求出删除改元素,前面+后面的1,最后返回max
代码
public static int longestSubarray(int[] nums) {
int[] array1 = new int[nums.length];
int[] array2 = new int[nums.length];
array1[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] == 1) {
array1[i] = array1[i - 1] + 1;
} else {
array1[i] = 0;
}
}
array2[nums.length - 1] = nums[nums.length - 1];
for (int i = nums.length - 2; i >= 0; i--) {
if (nums[i] == 1) {
array2[i] = array2[i + 1] + 1;
} else {
array2[i] = 0;
}
}
int max = 0 + array2[1];
for (int i = 1; i < nums.length - 1; i++) {
max = Math.max(max, array1[i - 1] + array2[i + 1]);
}
max = Math.max(max, array1[nums[nums.length - 1]] + 0);
System.out.println(max);
return max;
}