leetcode 随笔18

更新ing

8.8

99. 恢复二叉搜索树

难度困难

二叉搜索树中序遍历之后得到的应该是一个递增的序列。先用中序遍历得到所有的数字序列,进行排序之后,再去遍历一遍树,把对应的值放入相应的位置就行了。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public void recoverTree(TreeNode root) {
        if(root == null){
            return;
        }
        List<Integer> list = new LinkedList<>();
        TreeNode temp = root;
        inorder(temp, list);
        Collections.sort(list);
        f(root, list);
    }

    public void f(TreeNode root, List<Integer> list){
        if(root == null){
            return ; 
        }
        f(root.left, list);
        root.val = list.remove(0);
        f(root.right, list);
    }


    public void inorder(TreeNode root, List<Integer> list){
        if(root == null){
            return ;
        }
        inorder(root.left, list);
        list.add(root.val);
        inorder(root.right, list);
    }

}

55. 跳跃游戏

难度中等

用一个boolean记录下我当前能不能到达某个位置。

class Solution {
    public boolean canJump(int[] nums) {
        int n = nums.length;
        if(n == 0){
            return true;
        }

        boolean[] dp = new boolean[n];
        dp[0] =true;
        for(int i = 0;i < n;i++){
            if(dp[i]){
                int step = nums[i];
                int end = i + step;
                for(int j = i;j < dp.length && j <= end;j++){
                    dp[j] = true;    
                }
            }
        }
        return dp[n - 1];
    }
}

56. 合并区间

难度中等

主要思路是利用一个map,key是左界,value是右界。如果输入的数组是有序的话,则就可以按以下的方式处理(判断下一个区间的左界是不是包含在某个区间中,如果在,就去尝试去更新右界)。

不过当输入的数组是无界的时候就需要考虑多种情况,所以我先对输入的数组进行排序。排序标准就是按左界从小到大排序,当左界相同时,则按右界进行从小到大排序(不过如果是按我之后的思路,可以让右界从大到小排序,测了下差别也不大)。

class Solution {
    public int[][] merge(int[][] intervals) {
        if(intervals.length == 0){
            return new int[0][0];
        }
        Map<Integer, Integer> map = new HashMap<>();
        Arrays.sort(intervals, new Comparator<int[]>(){
            public int compare(int[] a, int[] b){
                if(a[0] == b[0]){
                    return a[1] - b[1];
                }
                return a[0] - b[0];
            }
        });

        for(int i = 0;i < intervals.length;i++){
            int begin = intervals[i][0];
            int end = intervals[i][1];

            boolean find = false;
            for(Map.Entry<Integer, Integer> entry : map.entrySet()){
                if(begin >= entry.getKey() && begin <= entry.getValue()){
                    if(end > entry.getValue()){
                        map.put(entry.getKey(), end);
                    }
                    find = true;
                }
            }

            if(!find){
                map.put(begin, end);
            }
        }

        int index = 0;
        int[][] ans = new int[map.size()][2];
        for(Map.Entry<Integer, Integer> entry : map.entrySet()){
            ans[index][0] = entry.getKey();
            ans[index][1] = entry.getValue();
            index++;
        }
        return ans;
    }
}

8.9

78. 子集

难度中等

因为不包含重复元素,所以在操作时没有那么复杂。借助一个list,采取回溯算法就可以解决。

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        ans.add(new ArrayList<Integer>());
        getSubsets(nums, 0, ans, new LinkedList<Integer>());
        return ans;
    }

    public void getSubsets(int[] nums, int index, List<List<Integer>> ans, List<Integer> path){
        for(int i = index;i < nums.length;i++){
            path.add(nums[i]);
            ans.add(new LinkedList<>(path));
            getSubsets(nums, i + 1, ans, path);
            path.remove(path.size() - 1);
        }
    }
}

90. 子集 II

难度中等

最笨的办法就是每次都去判断有没有包含。包含的话就不重复加入。

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> ans = new ArrayList<>();
        ans.add(new ArrayList<Integer>());
        getSubsets(nums, 0, ans, new LinkedList<Integer>());
        return ans;
    }


    public void getSubsets(int[] nums, int index, List<List<Integer>> ans, List<Integer> path){
        for(int i = index;i < nums.length;i++){    
            path.add(nums[i]);
            if(!contains(ans, path)){
                ans.add(new LinkedList<>(path));
            }
            getSubsets(nums, i + 1, ans, path);
            path.remove(path.size() - 1);
        }
    }

    public boolean contains(List<List<Integer>> ans, List<Integer> path){
        if(ans.size() == 1){
            return false;
        }
        HashMap<Integer, Integer> map1 = getMap(path);
        int size = path.size();
        boolean find;
        for(List<Integer> temp : ans){
            find = true;
            HashMap<Integer, Integer> map2 = getMap(temp);
            if(map1.size() != map2.size()){
                find = false;
            }

            for(Map.Entry<Integer, Integer> entry : map1.entrySet()){
                if(!map2.containsKey(entry.getKey()) || entry.getValue() != map2.get(entry.getKey())){
                    find = false;
                }
            }
            if(find){
                return true;
            }        
        }
        return false;
    }

    public HashMap<Integer, Integer> getMap(List<Integer> list){
        HashMap<Integer, Integer> map = new HashMap<>();

        for(int num : list){
            if(map.containsKey(num)){
                map.put(num, map.get(num) + 1);
            }else{
                map.put(num, 1);
            }
        }
        return map;
    }
}

另一种就用到了排序。先进行排序。在每次判断时都去判断是不是相同的元素,如果是,则跳过。

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> ans = new ArrayList<>();
        ans.add(new ArrayList<Integer>());
        getSubsets(nums, 0, ans, new LinkedList<Integer>());
        return ans;
    }


    public void getSubsets(int[] nums, int index, List<List<Integer>> ans, List<Integer> path){
        for(int i = index;i < nums.length;i++){   
            if (i > index && nums[i] == nums[i - 1]) {
                continue;
            } 
            path.add(nums[i]);
            ans.add(new LinkedList<>(path));
            getSubsets(nums, i + 1, ans, path);
            path.remove(path.size() - 1);
        }
    }
}

8.11

79. 单词搜索

难度中等

深度优先遍历 + 回溯。总体来说不是特别难。

class Solution {
    public boolean exist(char[][] board, String word) {
        int row = board.length;
        if(row == 0){
            return word.length() == 0;
        }
        int column = board[0].length;

        for(int i = 0;i < row;i++){
            for(int j = 0;j < column;j++){
                dfs(board, i, j, 0, word, 
                    new boolean[row][column], new ArrayList<Character>());
                if(exist){
                    return true;
                }
            }
        }
        
        return false;
    }

    boolean exist = false;
    public void dfs(char[][] board, int i, int j, int index, String word, boolean[][] visited, List<Character> list){
        if(index == word.length()){
            exist = true;
            return ;
        }

        if(i >= 0 && j >=0 && i < board.length && j < board[0].length && 
        word.charAt(index) == board[i][j] && !visited[i][j]){
            visited[i][j] = true;

            list.add(board[i][j]);
            dfs(board, i + 1, j, index + 1, word, visited, list);
            if(exist){
                return ;
            }

            dfs(board, i - 1, j, index + 1, word, visited, list);
            if(exist){
                return ;
            }

            dfs(board, i, j + 1, index + 1, word, visited, list);
            if(exist){
                return ;
            }
            dfs(board, i, j - 1, index + 1, word, visited, list);
            if(exist){
                return ;
            }
            visited[i][j] = false;
            list.remove(list.size() - 1);
        }
    }
}

8.13

43. 字符串相乘

难度中等

自己的想法,两次遍历,分别用num1的第i位与num2的第j位进行相乘,之后在后面拼接上应该有的0的个数,把这个String存放在一个list中。最后把list所有值进行相加。

最后虽然所有的测试用例都跑过了,但是超时。

class Solution {
    public String add(String num1, String num2){
        int m = num1.length() - 1;
        int n = num2.length() - 1;

        int carry = 0;
        StringBuilder sb = new StringBuilder();
        
        while(m >= 0 || n >= 0 || carry > 0){
            int value1 = m >= 0 ? Integer.parseInt(String.valueOf(num1.charAt(m))) : 0;
            int value2 = n >= 0 ? Integer.parseInt(String.valueOf(num2.charAt(n))) : 0;

            int temp = value1 + value2 + carry;
            carry = temp / 10;
            sb.append(String.valueOf(temp % 10));

            m--;
            n--;
        }
        return sb.reverse().toString();
    }


    public String multiply(String num1, String num2) {
        if(num1.equals("0") || num2.equals("0")){
            return "0";
        }
        List<String> nums = new ArrayList<>();
        for(int i = num1.length() - 1; i >= 0;i--){
            int value1 = Integer.parseInt(String.valueOf(num1.charAt(i)));
            for(int j = num2.length() - 1;j >= 0;j--){
                int value2 = Integer.parseInt(String.valueOf(num2.charAt(j)));
                
                StringBuilder sb = new StringBuilder();
                sb.append(String.valueOf(value1 * value2));

                //后面有多少个0
                for(int m = 0;m < num1.length() - 1 - i + num2.length() - 1 - j;m++){
                    sb.append("0");
                }
                nums.add(sb.toString());
                // System.out.println(value1 + "-" + value2 + ":" + sb.toString());
            }
        }
        String ans = nums.get(0);
        while(nums.size() > 1){
            ans = add(nums.get(0), nums.get(1));
            // System.out.println(nums.get(0) + " + " + nums.get(1) + " = " + ans);
            nums.remove(0);
            nums.remove(0);
            nums.add(0, ans);
        }
        return ans;
    }
}

看了题解之后,发现它可以直接利用乘法来实现。(不过它的转移过程有点看不懂)

class Solution {
    public String multiply(String num1, String num2) {
        if (num1.equals("0") || num2.equals("0")) {
            return "0";
        }
        int m = num1.length(), n = num2.length();
        int[] ansArr = new int[m + n];
        for (int i = m - 1; i >= 0; i--) {
            int x = num1.charAt(i) - '0';
            for (int j = n - 1; j >= 0; j--) {
                int y = num2.charAt(j) - '0';
                ansArr[i + j + 1] += x * y;
            }
        }
        for (int i = m + n - 1; i > 0; i--) {
            ansArr[i - 1] += ansArr[i] / 10;
            ansArr[i] %= 10;
        }
        int index = ansArr[0] == 0 ? 1 : 0;
        StringBuffer ans = new StringBuffer();
        while (index < m + n) {
            ans.append(ansArr[index]);
            index++;
        }
        return ans.toString();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值