zoukankan      html  css  js  c++  java
  • Candy [leetcode] O(n)时间复杂度,O(1)空间复杂度的方法

    对于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为递增和递减序列交际处的元素相应糖果数。应该是递增序列长度和递减序列长度中较大的值

    代码例如以下:

        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; 
        }


  • 相关阅读:
    [JSOI2012][bzoj4332] 分零食 [FFT]
    [MUTC2013][bzoj3513] idiots [FFT]
    [bzoj4259][bzoj4503] 残缺的字符串 [FFT]
    [bzoj3160] 万径人踪灭 [FFT+manacher]
    [AHOI2017/HNOI2017][bzoj4827] 礼物 [FFT]
    [ZJOI2014][bzoj3527]力 [FFT]
    [CQOI2012][bzoj2668] 交换棋子 [费用流]
    [CQOI2014][bzoj3504] 危桥 [最大流]
    [ZJOI2011][bzoj2229] 最小割 [最小割树]
    移动游戏ui设计(一)
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/4053466.html
Copyright © 2011-2022 走看看