Where is Vasya?
Where is Vasya?
Vasya stands in line with number of people p (including Vasya)
, but he doesn't know exactly which position he occupies. He can say that there are no less than b
people standing in front of him and no more than a
people standing behind him. Find the number of different positions Vasya can occupy.
Input
As an input you have 3 numbers:
1. Total amount of people in the line;
2. Number of people standing in front of him
3. Number of people standing behind him
Examples
Line.WhereIsHe(3, 1, 1) // => 2 The possible positions are: 2 and 3
Line.WhereIsHe(5, 2, 3) // => 3 The possible positions are: 3, 4 and 5
The third parameter is not irrelavant and is the reason why (9,4,3) is 4 not 5
you have to satisfy both conditions
no less than bef people in front of him
and
no more than aft people behind him
as far as i can tell all the test cases are correct
9个人,前面的人不少于4个,后面的人不多于3个的话,可以占据6,7,8,9 是个位置
第五个位置,虽然前面是4个人,但是后面也是4个人。后面的人数超过3了,就不符合。
using System; public class Line { public static int WhereIsHe(int p, int bef ,int aft) { // Your code is here... int count=0; int a=0;//people infront of him int b=0;//people behind him for(int i=1;i<=p;i++) { a=i-1; b=p-i; if(a>=bef&&b<=aft) { count++; } } return count; } }
使用Linq进行简化后:
using System; using System.Linq; public static int WhereIsHe(int p, int bef, int aft) { return Enumerable.Range(1, p).Where(x => x - 1 >= bef && p - x <= aft).Count(); }
其他人的解法
using System; public class Line { public static int WhereIsHe(int p, int bef ,int aft) { return Math.Min(p-bef,aft+1); } }
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了