Leetcode-1523. 在区间范围内统计奇数数目:
难度:简单
给你两个非负整数 low 和 high 。请你返回 low 和 high 之间(包括二者)奇数的数目。
示例 1:
输入:low = 3, high = 7
输出:3
解释:3 到 7 之间奇数数字为 [3,5,7] 。
示例 2:
输入:low = 8, high = 10
输出:1
解释:8 到 10 之间奇数数字为 [9] 。
提示:0 <= low <= high <= 10^9
解题
这也太简单了,直接一个for循环%2 ++秒杀
代码:
public int countOdds(int low, int high) {
int res = 0;
for (int i = low; i <= high; i++) {
if (i % 2 == 1) res++;
}
return res;
}
直接寄了,报超时长
![](https://i-blog.csdnimg.cn/blog_migrate/4c09c6949b5f37227e7083aee26bcd43.png)
说实话,我瞬间气吐了,这就是算法吗?
思考了下,作差可以吗?low和high分三种情况讨论
low和high两个都是奇数,double odd
low和high两个都是偶数,double even
low和high一个奇数一个偶数
算法是:high减去low然后再减1 除 2
代码:
public int countOdds(int low, int high) {
int res = 0;
// count double even
if (low % 2 == 0 && high % 2 == 0) {
res = (high - low) / 2;
}
// count double odd
else if (low % 2 == 1 && high % 2 == 1) {
res = (high - low - 1) / 2;
res += 2;
}
else{
res = (high - low - 1) / 2;
res++;
}
return res;
}
提交,继续寄,让我康康什么case过不了
![](https://i-blog.csdnimg.cn/blog_migrate/1cd8a857645757929076ab0a63c0af7c.png)
看来是缺了个相同的low和high判断,那就给你加个判断吧,只能这样了。
public int countOdds(int low, int high) {
int res = 0;
// count double even
if (low % 2 == 0 && high % 2 == 0) {
res = (high - low) / 2;
}
// count double odd
else if (low % 2 == 1 && high % 2 == 1) {
// special case
if(low == high) return 1;
res = (high - low - 1) / 2;
res += 2;
}
else{
res = (high - low - 1) / 2;
res++;
}
return res;
}
Leetcode-28. 实现strStr():
难度:简单
实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。
示例 1:
输入:haystack = "hello", needle = "ll"
输出:2
示例 2:
输入:haystack = "aaaaa", needle = "bba"
输出:-1
提示:
0 <= haystack.length, needle.length <= 5 * 10^4
haystack 和 needle 仅由小写英文字符组成
学习时间:
提示:这里可以添加计划学习的时间
例如:
1、 周一至周五晚上 7 点—晚上9点
2、 周六上午 9 点-上午 11 点
3、 周日下午 3 点-下午 6 点
学习产出:
提示:这里统计学习计划的总量
例如:
1、 技术笔记 2 遍
2、CSDN 技术博客 3 篇
3、 学习的 vlog 视频 1 个