LeetCode热题100道-day005

80 阅读1分钟

LeetCode热题100道-day005

1. 二级标题

1769. 移动所有球到每个盒子所需的最小操作数

  • 每当发现boxes字符串中存在字符“1”时,则针对这个位置计算每一个盒子的操作数。当遍历完boxes中所有字符之后,再针对于每个盒子,执行操作数的sum求和即可。
class Solution {  
    public int[] minOperations(String boxes) {  
        int[] result = new int[boxes.length()];  
        for (int i = 0; i < boxes.length(); i++) {  
            if (boxes.charAt(i) == '0') continue;  
            for (int j = 0; j < result.length; j++)  
                result[j] += Math.abs(j - i); // 当发现字符为'1'时,计算每个盒子的操作数。  
        }  
        return result;  
    }  
}

2. 全排列

46. 全排列

  • 回溯
class Solution {  
    public List<List<Integer>> permute(int[] nums) {  
        List<List<Integer>> res = new ArrayList<List<Integer>>();  
  
        List<Integer> output = new ArrayList<Integer>();  
        for (int num : nums) {  
            output.add(num);  
        }  
  
        int n = nums.length;  
        backtrack(n, output, res, 0);  
        return res;  
    }  
  
    public void backtrack(int n, List<Integer> output, List<List<Integer>> res, int first) {  
        // 所有数都填完了  
        if (first == n) {  
            res.add(new ArrayList<Integer>(output));  
        }  
        for (int i = first; i < n; i++) {  
            // 动态维护数组  
            Collections.swap(output, first, i);  
            // 继续递归填下一个数  
            backtrack(n, output, res, first + 1);  
            // 撤销操作  
            Collections.swap(output, first, i);  
        }  
    }  
}

3. 旋转图像

48. 旋转图像

  • 先水平翻转,再对角线翻转
class Solution {  
    public void rotate(int[][] matrix) {  
        int n = matrix.length;  
        // 水平翻转  
        for (int i = 0; i < n / 2; ++i) {  
            for (int j = 0; j < n; ++j) {  
                int temp = matrix[i][j];  
                matrix[i][j] = matrix[n - i - 1][j];  
                matrix[n - i - 1][j] = temp;  
            }  
        }  
        // 主对角线翻转  
        for (int i = 0; i < n; ++i) {  
            for (int j = 0; j < i; ++j) {  
                int temp = matrix[i][j];  
                matrix[i][j] = matrix[j][i];  
                matrix[j][i] = temp;  
            }  
        }  
    }  
}