对于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…
[LeetCode] Candy (分糖果),时间复杂度O(n),空间复杂度为O(1),且只需遍历一次的实现 原题: There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least…
先看看这个题目:某整形数组中除了两个单身整数外, 其余的整数都是成对出现的, 利用C代码求出这两个单身整数. 要求: 时间复杂度o(n), 空间复杂度o(1). 我们先用最傻瓜的方式来做吧: #include <iostream> using namespace std; // 时间复杂度为o(n^2), 空间复杂度为o(1), 不符合要求 void findSoleNumbers(int a[], int n, int &e1, int &e2) { int i = 0; i…
Candy There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more ca…
(1).把输入规模看成x轴,所花时间/空间看成y轴 O(n)就是y=x,y随x的增长而线性增长.也就是成正比,一条斜线. O(1)就是y=1,是一个常量,不管x怎么变,y不变,一条与x轴平行的线. (2).举个简单的例子,要从0加到n,我们会这么写: int sum = 0; for(int i = 0;i<=n;++i) { sum + = i; } 一共算了n次加法,那么就说这个时间复杂度是O(n).当然O(n)的精确的概念是,是n的最高次方,比如,某个计算共计算了3n+2次,那么这个时间复…
/* */ #include<iostream> #include<vector> //#include<algorithm> #include <windows.h> using namespace std; #define STOP system("pause"); #if 1 class Solution { public: int candy(vector<int> &ratings) { int len =…
题目: There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more cand…
There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies…
原理:使用三个指针,p,q指向交换的元素,r指向后续元素 代码如下: class Node{ int data; Node next; Node(int data){ this.data=data; } } Node reverse(Node head) { if(head==null || head.next==null) return head; Node p=head,q=p.next,r=q.next; q.next=p;p.next=null; while(r!=null){ p=q;…
#include <stdio.h> #include <iostream> using namespace std; long long fibs1(int in_iN) { ) { ; }) { ; }) { ; } ; ; ; ; while(t_k <= in_iN) { t_iValue = t_i1 + t_i2; t_i1 = t_i2; t_i2 = t_iValue; t_k ++; } return t_iValue; } long long fibs2(…