码迷,mamicode.com
首页 > 其他好文 > 详细

2020.7.19

时间:2020-07-19 15:49:30      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:data-   tco   判断   pre   没有   nbsp   tps   http   problem   

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;
    }
}

 

 

 

2020.7.19

标签:data-   tco   判断   pre   没有   nbsp   tps   http   problem   

原文地址:https://www.cnblogs.com/shish/p/13339359.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!