Candy [leetcode] O(n)时间复杂度,O(1)空间复杂度的方法
2014-10-27 09:35
441 查看
对于ratings[i+1],和ratings[i]的关系有下面几种:
1. 相等。相等时ratings[i+1]相应的糖果数为1
2.ratings[i + 1] > ratings[i]。在这样的情况下,要寻找以ratings[i]開始的递增序列。
3.ratings[i + 1] < ratings[i]。在这样的情况下,要寻找以ratings[i]開始的递减序列。
对于随意一个递增序列 [2 3 4 5 6] 相应的糖果数为 [1 2 3 4 X]
对于随意一个递减序列[6 5 4 3 2]相应的糖果数为[X 4 3 2 1]
X为递增和递减序列交际处的元素相应糖果数。应该是递增序列长度和递减序列长度中较大的值
代码例如以下:
1. 相等。相等时ratings[i+1]相应的糖果数为1
2.ratings[i + 1] > ratings[i]。在这样的情况下,要寻找以ratings[i]開始的递增序列。
3.ratings[i + 1] < ratings[i]。在这样的情况下,要寻找以ratings[i]開始的递减序列。
对于随意一个递增序列 [2 3 4 5 6] 相应的糖果数为 [1 2 3 4 X]
对于随意一个递减序列[6 5 4 3 2]相应的糖果数为[X 4 3 2 1]
X为递增和递减序列交际处的元素相应糖果数。应该是递增序列长度和递减序列长度中较大的值
代码例如以下:
int candy(vector<int> &ratings) { if (ratings.size() == 0) return 0; int sum = 0; int candyNum = 1; for (int i = 0; i < ratings.size() - 1;) { if (ratings[i] == ratings[i + 1]) { //if is the same rating, reset candy num. ie: 1 3 3, for the 2nd 3, candy num is 1 sum += candyNum;//add current candy num i++; candyNum = 1;//set next candy num to 1 } else if (ratings[i] < ratings[i + 1]) { // find ascending sequence, until i is the end of sequence. ie: 1 2 3 1, ratings[i] is 3 for (;i < ratings.size() - 1 && ratings[i] < ratings[i + 1]; i++) sum += (candyNum++); } else if (ratings[i] > ratings[i + 1]) { // find descending sequence, until i is the end of sequence. ie: 3 2 1 3, rating[i] is 1 int decCount = 1; for (; i < ratings.size() - 1 && ratings[i] > ratings[i + 1]; i++) sum += (decCount++); sum += max(candyNum, decCount);//add first element of the sequence //remove last element of the sequence, as i is the end of sequence, and i's candy num shouldn't be calculated into sum sum --; candyNum = 1; } } sum += candyNum; return sum; }
相关文章推荐
- Candy [leetcode] O(n)时间复杂度,O(1)空间复杂度的方法
- Candy [leetcode] O(n)时间复杂度,O(1)空间复杂度的方法
- [LeetCode] Candy (分糖果),时间复杂度O(n),空间复杂度为O(1),且只需遍历一次的实现
- [LeetCode] Candy (分糖果),时间复杂度O(n),空间复杂度为O(1),且只需遍历一次的实现
- Leetcode 234 Palindrome Linked List 复杂度为时间O(n) 和空间(1)解法
- LeetCode 第三题,官方给的标准答案的一个分析,利用空间换时间,将复杂度降到了O(n)
- 算法的时间复杂度和空间复杂度的求解方法
- LeetCode | 442. Find All Duplicates in an Array 限制时间复杂度O(n)空间复杂度O(1)的题
- 每天一道LeetCode-----找到序列中第一个没有出现的正整数,要求时间复杂度是O(n),空间复杂度是O(1)
- Leetcode 234 Palindrome Linked List 复杂度为时间O(n) 和空间(1)解法
- LeetCode 148. Sort List--O(nlogn)时间复杂度和常数空间复杂度给链表排序
- 七种排序方法(稳定性、空间复杂度、时间复杂度)分析总结
- 334.leetcode Increasing Triplet Subsequence(medium)[巧妙的方法减少时间与空间复杂度]
- [LeetCode] Set Matrix Zeroes (!!!!时间空间复杂度)
- 算法度量方法——时间复杂度及空间复杂度
- 各种排序方法的时间复杂度、空间复杂度和稳定性统计表
- bsd strtok实现和windowstrtok实现 NetBSD的方法是节约了空间,牺牲了时间(它的时间复杂度为N2) 而微软的方法是节约了时间(它的时间复杂度为N),牺牲了空间(开了一
- Leetcode:454. 4Sum II (解决时间和空间复杂度是关键)
- 时间复杂度和空间复杂度
- 时间复杂度和空间复杂度