博客记录-day165-力扣

70 阅读1分钟

一、力扣

1、矩阵中的最长递增路径

329. 矩阵中的最长递增路径

image.png

class Solution {
    int[][] direct = { { 1, 0 }, { -1, 0 }, { 0, -1 }, { 0, 1 } };
    int res;
    int[][] matrix;
    int[][] vis;
    int m, n;

    public int longestIncreasingPath(int[][] matrix) {
        m = matrix.length;
        n = matrix[0].length;
        vis = new int[m][n];
        this.matrix = matrix;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                dfs(i, j);
            }
        }
        return res;
    }

    public int dfs(int x, int y) {
        if (vis[x][y] != 0)
            return vis[x][y];
        int ans = 1;
        for (var dir : direct) {
            int nx = x + dir[0];
            int ny = y + dir[1];
            if (nx < 0 || nx >= m || ny < 0 || ny >= n)
                continue;
            if (matrix[nx][ny] > matrix[x][y])
                ans = Math.max(ans, dfs(nx, ny) + 1);
        }
        vis[x][y] = ans;
        res = Math.max(res, ans);
        return ans;
    }
}

2、缺失的第一个正数

41. 缺失的第一个正数

image.png

class Solution {
    public int firstMissingPositive(int[] nums) {
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            if (nums[i] <= 0) {
                nums[i] = n + 1;
            }
        }
        for (int i = 0; i < n; i++) {
            int target = Math.abs(nums[i]) - 1;
            if (target < n) {
                nums[target] = -Math.abs(nums[target]);
            }
        }
        for (int i = 0; i < n; i++) {
            if (nums[i] > 0) {
                return i + 1;
            }
        }
        return n + 1;
    }
}

3、数组中重复的数据

442. 数组中重复的数据

image.png

class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        int n = nums.length;
        List<Integer> res = new ArrayList<>();
        for (var x : nums) {
            int target = x - 1;
            while (target >= n)
                target -= n;
            nums[target] = nums[target] + n;
        }
        for (int i = 0; i < n; i++) {
            if (nums[i] > n * 2) {
                res.add(i + 1);
            }
        }
        return res;
    }
}

4、分发糖果

135. 分发糖果

image.png

class Solution {
    public int candy(int[] ratings) {
        int n = ratings.length;
        int[] left = new int[n];
        Arrays.fill(left, 1);
        for (int i = 1; i < n; i++) {
            if (ratings[i] > ratings[i - 1]) {
                left[i] = left[i - 1] + 1;
            }
        }
        int[] right = new int[n];
        Arrays.fill(right, 1);
        for (int i = n - 2; i >= 0; i--) {
            if (ratings[i] > ratings[i + 1]) {
                right[i] = right[i + 1] + 1;
            }
        }
        int res = 0;
        for (int i = 0; i < n; i++) {
            res += Math.max(left[i], right[i]);
        }
        return res;
    }
}