开发php网站开发,太湖网站建设推荐秒搜科技,手机版网站建设合同范本,百度一下就知道官方网站【问题描述】[中等]
求 12...n #xff0c;要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句#xff08;A?B:C#xff09;。输入: n 3
输出: 6【解答思路】
1. 递归#xff08;不合符题意#xff09; 时间复杂度#xff1a;O(N^2) 空间…【问题描述】[中等]
求 12...n 要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句A?B:C。输入: n 3
输出: 6
【解答思路】
1. 递归不合符题意 时间复杂度O(N^2) 空间复杂度O(N)
public int sumNums(int n) {if(n 1) return 1;n sumNums(n - 1);return n;
}
2. 逻辑运算符与递归 时间复杂度O(N) 空间复杂度O(N)
class Solution {int res 0;public int sumNums(int n) {boolean x n 1 sumNums(n - 1) 0;res n;return res;}
}class Solution {public int sumNums(int n) {boolean x n 1 (n sumNums(n - 1)) 0;return n;}
}3. 迭代不合符题意
循环必须使用 while 或 for 时间复杂度O(N) 空间复杂度O(1)
public int sumNums(int n) {int res 0;for(int i 1; i n; i)res i;return res;
}
4. 高斯求和公式不合符题意
高斯求和必须使用 乘除法 时间复杂度O(1) 空间复杂度O(1)
public int sumNums(int n) {return (1 n) * n / 2;
}【总结】
1.逻辑运算符短路效应 2. 思路往往从暴力开始到常规做法到逐步优化
3. Java中运算符优先级顺序 转载链接https://leetcode-cn.com/problems/qiu-12n-lcof/solution/mian-shi-ti-64-qiu-1-2-nluo-ji-fu-duan-lu-qing-xi-/