1. 程式人生 > 實用技巧 >leetcode——135.分發糖果

leetcode——135.分發糖果

暴力法,多次迴圈檢查,直到滿足條件。

public int candy(int[] ratings) {
        int[] candies = new int[ratings.length];
        Arrays.fill(candies,1);
        boolean flag = true;
        int sum = 0;
        while(flag){
            flag = false;
            for(int i = 0;i<ratings.length;i++){
                if
(i!=ratings.length -1 && ratings[i] >ratings[i+1] && candies[i] <= candies[i+1]){ candies[i] = candies[i+1] + 1; flag = true; } if(i>0 && ratings[i] > ratings[i-1] && candies[i] <= candies[i-1]){ candies[i]
= candies[i-1]+1; flag = true; } } } for(int candy: candies){ sum += candy; } return sum; }

挺慢的。。。。

方法二,用兩個陣列,這個方法和我自己的思路比較像

public int candy(int[] ratings) {
        int sum = 0;
        int[] left2right = new
int[ratings.length]; int[] right2left = new int[ratings.length]; Arrays.fill(left2right, 1); Arrays.fill(right2left, 1); for (int i = 1; i < ratings.length; i++) { if (ratings[i] > ratings[i - 1]) { left2right[i] = left2right[i - 1] + 1; } } for (int i = ratings.length - 2; i >= 0; i--) { if (ratings[i] > ratings[i + 1]) { right2left[i] = right2left[i + 1] + 1; } } for (int i = 0; i < ratings.length; i++) { sum += Math.max(left2right[i], right2left[i]); } return sum; }

——2020.7.13