「力扣」第 29 场双周赛代码(前 3 题)

比赛时间:北京时间 2020 年 6 月 27 日晚 10:30

再接再厉!

第 1 题:去掉最低工资和最高工资后的工资平均值

Java 代码:

public class Solution {

    public double average(int[] salary) {
        int len = salary.length;

        double sum = salary[0];
        int minVal = salary[0];
        int maxVal = salary[0];

        for (int i = 1; i < len; i++) {
            minVal = Math.min(minVal, salary[i]);
            maxVal = Math.max(maxVal, salary[i]);

            sum += salary[i];
        }
        return (sum - minVal - maxVal) / (len - 2);
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] salary = {8000, 9000, 2000, 3000, 6000, 1000};
        double res = solution.average(salary);
        System.out.println(res);
    }
}

第 2 题:n 的第 k 个因子

public class Solution {

    public int kthFactor(int n, int k) {
        if (n == 1 && k == 1) {
            return 1;
        }

        int count = 0;
        for (int i = 1; i <= n; i++) {
            if ((n % i) == 0) {
                count++;
                if (count == k) {
                    return i;
                }
            }
        }
        return -1;
    }
}

第 3 题:删掉一个元素以后全为 1 的最长子数组

public class Solution {

    public int longestSubarray(int[] nums) {

        int len = nums.length;
        int left = 0;
        int right = 0;

        int ones = 0;

        int maxCount = 0;
        int res = 0;

        while (right < len) {
            if (nums[right] == 1) {
                ones++;
            }
            maxCount = Math.max(maxCount, ones);
            right++;
            // System.out.println(maxCount);
            while (right - left > maxCount + 1) {
                if (nums[left] == 1) {
                    ones--;
                }
                left++;
            }
            res = Math.max(res, right - left);
        }
        return res - 1;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        // int[] nums = {1, 1, 0, 1};
        // int[] nums = {0, 1, 1, 1, 0, 1, 1, 0, 1};
        // int[] nums = {1, 1, 1};
        // int[] nums = {1, 1, 0, 0, 1, 1, 1, 0, 1};
        int[] nums = {0, 0, 0};
        int res = solution.longestSubarray(nums);
        System.out.println(res);
    }
}

你可能感兴趣的:(力扣,滑动窗口)