一、原题
链接:Training on Likes Vs Dislikes | Codewars
YouTube had a like and a dislike button, which allowed users to express their opinions about particular content. It was set up in such a way that you cannot like and dislike a video at the same time. There are two other interesting rules to be noted about the interface: Pressing a button, which is already active, will undo your press. If you press the like button after pressing the dislike button, the like button overwrites the previous "Dislike" state. The same is true for the other way round. |
二、解题
1、分析
1)前后不一致,后面覆盖前面
like_or_dislike([Dislike, Like]) ➞ Like
2) 前后一样,则为NOTHING
like_or_dislike([Like, Like]) ➞ Nothing
3)前面结果为NOTHONG, 以后面为主
like_or_dislike([Like, Like, Like]) ➞ Like
4)题中附带要求
- 如果当前没有按钮处于活动状态,则返回 。
Nothing
- 如果列表为空,则返回 。
Nothing
2、思路
1)思路一【此思路简单】
整体思想:将NOTHING与LIKE、DISLIKE放在同一地位思考,可发现,后面的与前面紧邻的不同,后面的就会将前面的覆盖。
方法:
(1)创建BUTTON(item) :enum button item=NOTHING;
(2)使item与events[n]逐个比较,按照原则将结果存入item中;
(3)返回item;
2)思路二【此思路颇为复杂】【“数字化”处理不当,化简为繁】
(1)列表为空,返回NOTHONG
(2)长度为一,直接返回
(3)当长度>=2时:
创建item=100;item==1表示LIKE,item==-1表示DISLIKE,item=NOTHING;
三 、Myway
【最大收获:好思路极大限度降低问题难度】
1、思路一代码
#include <stddef.h>enum button { NOTHING, LIKE, DISLIKE };enum button like_or_dislike (size_t n, const enum button events[n])
{ enum button item=NOTHING;for(size_t i=0;i<n;i++){if(events[i]!=item){item=events[i];}else if(events[i]==item){item=NOTHING;}}return item;}
2、思路二代码:
#include <stddef.h>enum button { NOTHING, LIKE, DISLIKE };enum button like_or_dislike (size_t n, const enum button events[n])
{ if(n<=0) return NOTHING;if(n==1){if(events[0]==LIKE){return LIKE;}if(events[0]==DISLIKE){//enum button events[0]==DISLIKE是错误的。return DISLIKE;}
} int item=100;for(int i=0;i<(int)(n-1);i++){if(events[i]==events[i+1]){if(item==0){if(events[i]==LIKE) item=1;else item=-1;}else item=0;}else{if(item==0){if(events[i+1]==LIKE){item=1;}else item=-1;}else if(item==1){if(events[i+1]==LIKE){item=0;}else item=-1;}else if(item==-1){if(events[i+1]==LIKE){item=1;}else item=0;}else{if(events[i+1]==LIKE) item=1;if(events[i+1]==DISLIKE) item=-1;}}}printf("%d\n",item);if(item==-1){return DISLIKE;}else if(item==1){return LIKE;}else if(item==0){return NOTHING;}}