本文主要是介绍LeetCode--135. Candy,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
https://leetcode.com/problems/candy/
解法一:
class Solution {public int candy(int[] ratings) {int[] candies=new int[ratings.length];Arrays.fill(candies,1);boolean flag=true;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;}}}int sum=0;for(int num:candies)sum+=num;return sum;}
}
解法二:
class Solution {public int candy(int[] ratings) {int[] leftCandies=new int[ratings.length];int[] rightCandies=new int[ratings.length];Arrays.fill(leftCandies,1);Arrays.fill(rightCandies,1);for(int i=1;i<ratings.length;i++){if(ratings[i]>ratings[i-1])leftCandies[i]=leftCandies[i-1]+1;}for(int i=ratings.length-2;i>=0;i--){if(ratings[i]>ratings[i+1])rightCandies[i]=rightCandies[i+1]+1;}int sum=0;for(int i=0;i<ratings.length;i++){sum+=Math.max(leftCandies[i],rightCandies[i]);}return sum;}}
解法三:
class Solution {public int candy(int[] ratings) {int[] candies=new int[ratings.length];Arrays.fill(candies,1);for(int i=1;i<ratings.length;i++){if(ratings[i]>ratings[i-1])candies[i]=candies[i-1]+1;}int sum=candies[ratings.length-1];for(int i=ratings.length-2;i>=0;i--){if(ratings[i]>ratings[i+1])candies[i]=Math.max(candies[i],candies[i+1]+1);sum+=candies[i];}return sum;}
}
这篇关于LeetCode--135. Candy的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!