Leetcode 第29场双周赛题解

5432. 去掉最低工资和最高工资后的工资平均值

思路:排序求和即可。

class Solution {
    public double average(int[] salary) {

        double ans = 0;
        Arrays.sort(salary);

        for (int i = 1; i < salary.length - 1; i++)
            ans += salary[i];

        return ans / (salary.length - 2);

    }
}

5433. n 的第 k 个因子

思路:枚举n的因子即可,

class Solution {
    public int kthFactor(int n, int k) {

        List list = new ArrayList<>();

        for (int i = 1; i <= n; i++)
            if (n % i == 0) {
                list.add(i);
            }

        if (list.size() < k) return -1;

        return list.get(k - 1);

    }
}

5434. 删掉一个元素以后全为 1 的最长子数组

思路:首先求一波前缀和,然后枚举子数组的右端点,然后二分左端点的位置,能够满足的条件的左端点l+1是sum[r]-sum[l]+1>=r-l+1。

class Solution {
    public int longestSubarray(int[] nums) {

        int n = nums.length;
        int ans = 0;
        int[] sum = new int[n];

        sum[0] = nums[0];
        for (int i = 1; i < n; i++)
            sum[i] = sum[i - 1] + nums[i];

        for (int i = 0; i < n; i++) {
            if(sum[i]>=i){
                ans=Math.max(ans,i);
                continue;
            }
            int l = 0, r = i, p = -1;
            while (l <= r) {
                int mid = (l + r) / 2;
                if (sum[i] - sum[mid] + 1 >= i - mid) {
                    p = mid;
                    r = mid - 1;
                } else
                    l = mid + 1;
            }
            if (p == i && nums[i] == 0 || p == -1)
                continue;
            ans = Math.max(ans, i-p-1);
        }

        return ans;

    }
}

5435. 并行课程 II

思路:可能很多人上来第一感觉就是拓扑排序,并基于拓扑排序衍生出贪心思想,例如:我们优先学习入度为0并且以该课程向下遍历深度需满足当前最大.....还有其他的贪心思想,这些在比赛时一一找到了反例,本题考查的仍然是动态规划,因此我们老老实实动归就好啦,n只有15这么大,妥妥的状压dp呀。

class Solution {
    public int minNumberOfSemesters(int n, int[][] dependencies, int k) {

        int[] edges = new int[n];
        int[] nums = new int[1 << n];
        int[] dp = new int[1 << n];

        for (int i = 1; i < (1 << n); i++) {
            dp[i] = 2000000;
            nums[i] = nums[i >> 1] + (i & 1);
        }
        for (int i = 0; i < dependencies.length; i++)
            edges[dependencies[i][1] - 1] |= 1 << dependencies[i][0] - 1;

        for (int i = 0; i < (1 << n); i++) {
            int j = 0, l = 0;
            for (; j < n; j++)
                if ((i >> j & 1) == 0 && (edges[j] & i) == edges[j])
                    l |= 1 << j;
            for (j = l; j > 0; j = j - 1 & l)
                if (nums[j] <= k)
                    dp[i | j] = Math.min(dp[i | j], dp[i] + 1);
        }

        return dp[(1 << n) - 1];

    }
}

 

你可能感兴趣的:(Leetcode 第29场双周赛题解)