zoukankan      html  css  js  c++  java
  • 2020.7.19

    406. 根据身高重建队列

    贪心算法

    思路参考:https://leetcode-cn.com/problems/queue-reconstruction-by-height/solution/gen-ju-shen-gao-zhong-jian-dui-lie-by-leetcode/

    第一次在排序的时候没有考虑如果同样高度,判断排序的位置

    如下错误代码:

            Arrays.sort(people, new Comparator<int[]>() {
                @Override
                public int compare(int[] o1, int[] o2) {
                    if(o1[0] < o2[0]) return 1;
                    else if(o1[0] > o2[0]) return -1;
                    else return 0;
                }
            });

    修改成:

    class Solution {
     public int[][] reconstructQueue(int[][] people) {
            Arrays.sort(people, new Comparator<int[]>() {
                @Override
                public int compare(int[] o1, int[] o2) {
                    return o1[0] == o2[0] ? o1[1] - o2[1] : o2[0] - o1[0];
                }
            });
            int n = people.length;
            List<int[]> list = new ArrayList<int[]>();
            for (int i = 0; i < n; i++) {
                list.add(people[i][1], people[i]);
            }
            return  list.toArray(new int[n][2]);
        }
    }

    python

        def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
            # 注意排序的用法
            people.sort(key = lambda x: (-x[0], x[1]))
            list = []
            for x in people:
                list.insert(x[1], x)
            return list

    43. 字符串相乘

    class Solution {
        public String multiply(String num1, String num2) {
            if(num1.equals("0") || num2.equals("0"))return "0";
            char[] charArr1 = num1.trim().toCharArray();
            char[] charArr2 = num2.trim().toCharArray();
            int n = num1.length(), m = num2.length();
            int[] arr1 = new int[n];
            int[] arr2 = new int[m];
            for (int i = 0; i < n; i++) {
                arr1[i] = charArr1[i] - '0';
            }
            for (int i = 0; i < m; i++){
                arr2[i] = charArr2[i] - '0';
            }
    
            int[] res = new int[m + n];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    res[i+j+1] += arr1[i] * arr2[j];
                }
            }
            for (int i = res.length - 1; i > 0 ; i--) {
                if(res[i] >= 10 && i != 1){
                    res[i - 1] += res[i] / 10;
                    res[i] %= 10;
                }
            }
            String resultStr = "";
            for (int i = 1; i < res.length; i++) {
                resultStr += ""+res[i];
            }
            return resultStr;
        }
    }

  • 相关阅读:
    EM
    te2
    te
    XLnet
    GPT
    40.Properties
    38.特殊操作流
    37.I/O流
    35.File
    day68日考
  • 原文地址:https://www.cnblogs.com/shish/p/13339359.html
Copyright © 2011-2022 走看看