「力扣」第 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);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章