leetcode candy
2014-08-22 20:29
309 查看
这道题折腾了好久,一开始想复杂了。比较好理解的一个方法是通过两次遍历。
注意到一个事实:只有当当前孩子比旁边孩子高的时候才会要求比他更多的糖,而这个比当前孩子矮的孩子既有可能来自左边,也有可能来自右边。
也就是说,左右两边的孩子都会对当前孩子做出限定。当每个孩子既能满足左边孩子的限定又能满足右边孩子的限定的时候,分配的糖果才是符合要求的。
注意第二次遍历的时候,使得当前孩子糖果数目增多的条件又多了一个(count[i] <= count[i +1]),那是因为第一次遍历的时候,所有孩子都只有一个糖果,所以这个条件直接成立。
但第二次面临的是已经经过修改后的数据。
ac之后又在讨论区发现一种更巧妙的一次遍历方法:
这个算法的为什么成立我还没搞明白,有待继续探索。
注意到一个事实:只有当当前孩子比旁边孩子高的时候才会要求比他更多的糖,而这个比当前孩子矮的孩子既有可能来自左边,也有可能来自右边。
也就是说,左右两边的孩子都会对当前孩子做出限定。当每个孩子既能满足左边孩子的限定又能满足右边孩子的限定的时候,分配的糖果才是符合要求的。
int candy(vector<int> &ratings){ int size = ratings.size(); vector<int> count(size, 1); if (size == 0) return 0; else if (size == 1) return 1; for (int i = 1; i < size; i++){ if (ratings[i] > ratings[i - 1]){ count[i] = count[i - 1] + 1; } } for (int i = size - 2; i >= 0; i--){ if (ratings[i] > ratings[i + 1] && count[i] <= count[i + 1]){ count[i] = count[i + 1] + 1; } } int result = 0; for (int i = 0; i < size; i++){ result += count[i]; } return result; }
注意第二次遍历的时候,使得当前孩子糖果数目增多的条件又多了一个(count[i] <= count[i +1]),那是因为第一次遍历的时候,所有孩子都只有一个糖果,所以这个条件直接成立。
但第二次面临的是已经经过修改后的数据。
ac之后又在讨论区发现一种更巧妙的一次遍历方法:
int candy(vector<int> &ratings) { // Note: The Solution object is instantiated only once and is reused by each test case. int nCandyCnt = 0;///Total candies int nSeqLen = 0; /// Continuous ratings descending sequence length int nPreCanCnt = 1; /// Previous child's candy count int nMaxCntInSeq = nPreCanCnt; if (ratings.begin() != ratings.end()) { nCandyCnt++;//Counting the first child's candy. for (vector<int>::iterator i = ratings.begin() + 1; i != ratings.end(); i++) { // if r[k]>r[k+1]>r[k+2]...>r[k+n],r[k+n]<=r[k+n+1], // r[i] needs n-(i-k)+(Pre's) candies(k<i<k+n) // But if possible, we can allocate one candy to the child, // and with the sequence extends, add the child's candy by one // until the child's candy reaches that of the prev's. // Then increase the pre's candy as well. // if r[k] < r[k+1], r[k+1] needs one more candy than r[k] // if (*i < *(i - 1)) { //Now we are in a sequence nSeqLen++; if (nMaxCntInSeq == nSeqLen) { //The first child in the sequence has the same candy as the prev //The prev should be included in the sequence. nSeqLen++; } nCandyCnt += nSeqLen; nPreCanCnt = 1; } else { if (*i > *(i - 1)) { nPreCanCnt++; } else { nPreCanCnt = 1; } nCandyCnt += nPreCanCnt; nSeqLen = 0; nMaxCntInSeq = nPreCanCnt; } } } return nCandyCnt; }
这个算法的为什么成立我还没搞明白,有待继续探索。
相关文章推荐
- LeetCode: Candy
- leetcode Candy
- leetCode_Candy
- [LeetCode][Java] Candy
- Leetcode 之Candy 分糖果问题。
- Candy - LeetCode
- LeetCode——Candy
- leetcode:Candy 【Java】
- Leetcode. 135 Candy(Hard)
- [LeetCode]Candy——分糖果问题
- Candy - Leetcode
- 【LeetCode】Candy
- [Leetcode][JAVA] Candy
- LeetCode题解:Candy
- Leetcode 135 Candy 解题报告
- [LeetCode]题解(python):135-Candy
- 【Leetcode】Candy
- LeetCode | Candy(分糖果问题)
- Leetcode-candy
- leetcode第16题(candy)