diff --git a/problems/0035.搜索插入位置.md b/problems/0035.搜索插入位置.md index 1fc07143..a536f0ec 100644 --- a/problems/0035.搜索插入位置.md +++ b/problems/0035.搜索插入位置.md @@ -76,7 +76,7 @@ public: ``` 时间复杂度:O(n) -时间复杂度:O(1) +空间复杂度:O(1) 效率如下: @@ -238,16 +238,16 @@ Python: ```python3 class Solution: def searchInsert(self, nums: List[int], target: int) -> int: - left, right = 0, len(nums) - 1 - + left, right = 0, len(nums) - 1 + while left <= right: middle = (left + right) // 2 - + if nums[middle] < target: left = middle + 1 elif nums[middle] > target: right = middle - 1 - else: + else: return middle return right + 1 ``` diff --git a/problems/0070.爬楼梯完全背包版本.md b/problems/0070.爬楼梯完全背包版本.md index a2a5ca32..f7a80f3b 100644 --- a/problems/0070.爬楼梯完全背包版本.md +++ b/problems/0070.爬楼梯完全背包版本.md @@ -88,7 +88,8 @@ 以上分析完毕,C++代码如下: -``` + +```cpp class Solution { public: int climbStairs(int n) { diff --git a/problems/0494.目标和.md b/problems/0494.目标和.md index 77b3c76d..5d89f7dc 100644 --- a/problems/0494.目标和.md +++ b/problems/0494.目标和.md @@ -19,15 +19,15 @@ 示例: -输入:nums: [1, 1, 1, 1, 1], S: 3 -输出:5 +输入:nums: [1, 1, 1, 1, 1], S: 3 +输出:5 -解释: --1+1+1+1+1 = 3 -+1-1+1+1+1 = 3 -+1+1-1+1+1 = 3 -+1+1+1-1+1 = 3 -+1+1+1+1-1 = 3 +解释: +-1+1+1+1+1 = 3 ++1-1+1+1+1 = 3 ++1+1-1+1+1 = 3 ++1+1+1-1+1 = 3 ++1+1+1+1-1 = 3 一共有5种方法让最终目标和为3。 @@ -202,6 +202,7 @@ public: for (int i = 0; i < nums.size(); i++) sum += nums[i]; if (S > sum) return 0; // 此时没有方案 if ((S + sum) % 2 == 1) return 0; // 此时没有方案 + if (S + sum < 0) return 0; // 以确保bagSize为正数 int bagSize = (S + sum) / 2; vector dp(bagSize + 1, 0); dp[0] = 1; @@ -311,7 +312,7 @@ Javascript: const findTargetSumWays = (nums, target) => { const sum = nums.reduce((a, b) => a+b); - + if(target > sum) { return 0; }