2020.7.19
Posted shish
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2020.7.19相关的知识,希望对你有一定的参考价值。
406. 根据身高重建队列
贪心算法
第一次在排序的时候没有考虑如果同样高度,判断排序的位置
如下错误代码:
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的主要内容,如果未能解决你的问题,请参考以下文章