> 文档中心 > 力扣第 294 场周赛回顾(前三题)

力扣第 294 场周赛回顾(前三题)


力扣第 294 场周赛回顾

第一题:

字母在字符串中的百分比
给你一个字符串 s 和一个字符 letter ,返回在 s 中等于 letter 字符所占的 百分比 ,向下取整到最接近的百分比。

这题比较简单,我的方案是用for循环比较数组的每一个元素,如果相等就把num++,最后直接算出来百分比。

class Solution {   public static int percentageLetter(String s, char letter) { char[] chars = s.toCharArray(); int num = 0; String let =  String.valueOf(letter); for(int i = 0;i < chars.length;i++) {     String tmp = String.valueOf(chars[i]);     if(tmp.equals(let)) {  num++;     } } return (num*100/chars.length);    }}

第二题

装满石头的背包的最大数量

定义一个数组tmp表示第i个背包剩余的容量,然后算出每一个背包的剩余容量,并且存放在tmp数组里,然后把tmp数组排序(这样就可以从小到大的遍历背包的剩余容量)。遍历tmp数组,如果第i个背包容量小于等于additionalRocks,将tmp[i]数组清零,并且additionalRocks 的值减去tmp[i]。最后遍历tmp数组,返回tmp数组中的值等于0的个数。

class Solution {    public int maximumBags(int[] capacity, int[] rocks, int additionalRocks) { int num = capacity.length; int[] tmp = new int[num]; int res = 0; for(int i = 0;i < num;i++) {     tmp[i] = capacity[i] - rocks[i]; }  Arrays.sort(tmp); for(int i = 0;i < num;i++) {     if(additionalRocks >= tmp[i]) {  additionalRocks -= tmp[i];  tmp[i] = 0;     }else {  tmp[i] = tmp[i] - additionalRocks;  break;     } } for(int i = 0;i < num;i++) {     if(tmp[i] == 0) {  res++;     } } return res;    }}

第三题

表示一个折线图的最少线段数

这道题我的方案是根据斜率判断线段是否发生了转折,这道题需要有两个要注意的地方,一个是要对stockPrices数组根据每行的第一列排序,不然斜率可能会出现相同的情况,第二个要注意的点是利用斜率判断时要用乘法来判断,不要用除法判断,不然会出现精度不够的情况,在竞赛时就会一种这样:
在这里插入图片描述

什么是乘法什么是除法呢?
假设有三个点(x0,y0)(x1,y1)(x2,y2)我们判断三点是否在一条直线可以利用斜率判断,即(y1 - y0)/(x1 - x0)== (y2 - y0)/(x2 - x0)。但是除法会出现精度问题,即两个斜率很接近但是他们的小数点后前几位是相同的,这样是计算机是判断不出来的,用乘法可以解决这个问题,即判断(y1 - y0)*(x2 - x0)== (y2 - y0)*(x1 - x0)

class Solution {    public int minimumLines(int[][] stockPrices) { int num = stockPrices.length; if(num == 1) {     return 0; }Arrays.sort(stockPrices, new Comparator<int[]>(){     public int compare(int[] o1, int[] o2) {  return o1[0] - o2[0];     } });  int res = 1; for(int i = 2;i < num;i++) {     long x0 = stockPrices[i - 2][0],y0 = stockPrices[i - 2][1];     long x1 = stockPrices[i - 1][0],y1 = stockPrices[i - 1][1];     long x2 = stockPrices[i - 0][0],y2 = stockPrices[i - 0][1];     if((y1 - y0)*(x2 - x1) != (y2 - y1)*(x1 - x0)) {  res++;     } } return res; }}

第四题

没有ac还没有看。以后再补。