Day 32 | 122. Best Time to Buy and Sell Stock II | 55. Jump Game | 45. Jump Game II

该文记录了LeetCode中一系列与数组、链表相关的编程挑战,包括买卖股票的最佳时机、跳跃游戏、最大跳跃数等,展示了如何运用算法解决这些经典问题。

Day 1 | 704. Binary Search | 27. Remove Element | 35. Search Insert Position | 34. First and Last Position of Element in Sorted Array
Day 2 | 977. Squares of a Sorted Array | 209. Minimum Size Subarray Sum | 59. Spiral Matrix II
Day 3 | 203. Remove Linked List Elements | 707. Design Linked List | 206. Reverse Linked List
Day 4 | 24. Swap Nodes in Pairs| 19. Remove Nth Node From End of List| 160.Intersection of Two Lists
Day 6 | 242. Valid Anagram | 349. Intersection of Two Arrays | 202. Happy Numbe | 1. Two Sum
Day 7 | 454. 4Sum II | 383. Ransom Note | 15. 3Sum | 18. 4Sum
Day 8 | 344. Reverse String | 541. Reverse String II | 替换空格 | 151.Reverse Words in a String | 左旋转字符串
Day 9 | 28. Find the Index of the First Occurrence in a String | 459. Repeated Substring Pattern
Day 10 | 232. Implement Queue using Stacks | 225. Implement Stack using Queue
Day 11 | 20. Valid Parentheses | 1047. Remove All Adjacent Duplicates In String | 150. Evaluate RPN
Day 13 | 239. Sliding Window Maximum | 347. Top K Frequent Elements
Day 14 | 144.Binary Tree Preorder Traversal | 94.Binary Tree Inorder Traversal| 145.Binary Tree Postorder Traversal
Day 15 | 102. Binary Tree Level Order Traversal | 226. Invert Binary Tree | 101. Symmetric Tree
Day 16 | 104.MaximumDepth of BinaryTree| 111.MinimumDepth of BinaryTree| 222.CountComplete TreeNodes
Day 17 | 110. Balanced Binary Tree | 257. Binary Tree Paths | 404. Sum of Left Leaves
Day 18 | 513. Find Bottom Left Tree Value | 112. Path Sum | 105&106. Construct Binary Tree
Day 20 | 654. Maximum Binary Tree | 617. Merge Two Binary Trees | 700.Search in a Binary Search Tree
Day 21 | 530. Minimum Absolute Difference in BST | 501. Find Mode in Binary Search Tree | 236. Lowes
Day 22 | 235. Lowest Common Ancestor of a BST | 701. Insert into a BST | 450. Delete Node in a BST
Day 23 | 669. Trim a BST | 108. Convert Sorted Array to BST | 538. Convert BST to Greater Tree
Day 24 | 77. Combinations
Day 25 | 216. Combination Sum III | 17. Letter Combinations of a Phone Number
Day 27 | 39. Combination Sum | 40. Combination Sum II | 131. Palindrome Partitioning
Day 28 | 93. Restore IP Addresses | 78. Subsets | 90. Subsets II
Day 29 | 491. Non-decreasing Subsequences | 46. Permutations | 47. Permutations II
Day 30 | 332. Reconstruct Itinerary | 51. N-Queens | 37. Sudoku Solver
Day 31 | 455. Assign Cookies | 376. Wiggle Subsequence | 53. Maximum Subarray


LeetCode 122. Best Time to Buy and Sell Stock II

Question Link

class Solution {
    public int maxProfit(int[] prices) {
        int result = 0;
        for(int i = 1; i < prices.length; i++){
            int profit = prices[i] - prices[i - 1];
            if(profit > 0)
                result += profit;
        }
        return result;
    }
}
  • We can decompose the final profit by day. The max profit is the sum of the profit of days whose profit is positive.

LeetCode 55. Jump Game

Question Link

class Solution {
    public boolean canJump(int[] nums) {
        int coverRange = 0;
        for(int i = 0; i <= coverRange; i++){
            coverRange = Math.max(coverRange, i + nums[i]);
            if(coverRange >= nums.length - 1)
                return true;
        }

        return false;
    }
}
  • The initial cover range should be 0
  • We only can update the cover range when i in the cover range

LeetCode 45. Jump Game II

Question Link

class Solution {
    public int jump(int[] nums) {
        if(nums == null || nums.length == 0 || nums.length == 1)
            return 0;
        // The number of jumps
        int count = 0;
        // The current cover range
        int curDistance = 0;
        // The max cover range
        int maxDistance = 0;
        for(int i = 0; i < nums.length; i++){
            maxDistance = Math.max(maxDistance, i + nums[i]);
            // Jump one more step can reach the end position.
            if(maxDistance >= nums.length - 1){
                count++;
                break;
            }
            // Update the distance that the next step can reach when reaching the current max cover range
            if(curDistance == i){
                count++;
                curDistance = maxDistance;
            }
        }
        return count;
    }
}
  • Jump one more step can reach the end position.
  • Update the distance that the next step can reach when reaching the current max cover range
<think> 我们注意到在之前的代码中,我们通过以下方式传递了TimeType参数: queryJson: JSON.stringify({ ...this.queryParams, TimeType: this.queryParams.TimeType || 'day' // 默认按天分组 }) 但是,在Vue的data中,queryParams.TimeType初始值为空字符串,当用户没有选择时,我们需要提供一个默认值'day'。 然而,在代码中我们使用了逻辑或运算符`||`,如果`this.queryParams.TimeType`为空字符串(假值),则会使用'day'。这符合我们的预期。 但是,这里有一个潜在的问题:在搜索时,如果用户选择了分类方式(比如'day'),那么`this.queryParams.TimeType`就是'day';如果用户没有选择,那么就是空字符串,我们使用默认值'day'。所以没有问题。 然而,在初始化时,我们可能希望默认显示按天分组的数据,但是页面加载后,分类方式下拉框是空白的,这可能会让用户困惑。因此,我们可以考虑在data中给TimeType一个初始值'day',这样下拉框就会默认选中“天”。 所以,我们修改两处: 1. 在data中,将queryParams.TimeType的初始值设为'day' 2. 在getPageList方法中,我们仍然保留默认值处理,以防在某个时刻TimeType为空(虽然现在不会了,但为了健壮性保留) 修改如下: 在data中: ```javascript data: function () { return { // ... 其他数据 ... queryParams: { F_Status: -10, TimeType: 'day', // 默认选择“天” DateArr: [], // ... 其他 ... }, // ... 其他数据 ... } } ``` 在getPageList方法中,我们保留默认值处理(虽然现在TimeType已经有默认值,但以防万一): ```javascript getPageList() { const params = { pagination: JSON.stringify(this.pageConfig), queryJson: JSON.stringify({ ...this.queryParams, TimeType: this.queryParams.TimeType || 'day' // 仍然保留,确保有值 }) } // ... 其他代码 ... } ``` 同时,在模板中,el-select绑定的v-model是queryParams.TimeType,所以默认会显示“天”。 另外,我们还需要注意,在搜索按钮点击事件searchData中,我们调用了getPageList,所以会使用当前选中的TimeType。 但是,在页面初始化时,我们并没有在created或mounted中调用getPageList(在mounted中注释掉了),所以我们需要在初始化数据后立即加载一次数据。 观察代码,在created中调用了initData,在initData中我们获取了一些字典数据,但并没有调用getPageList。因此,我们需要在created中或者initData完成后调用一次getPageList。 我们可以在initData的异步操作完成后调用,但由于异步操作有多个,我们可以选择在created中直接调用一次getPageList,或者在initData中最后调用。 这里我们选择在created中,在initData之后调用一次getPageList(因为initData是同步执行,但内部有异步操作,所以不能保证异步操作完成)。因此,我们可以将初始加载数据的逻辑放在mounted中,并取消注释。 修改mounted: ```javascript mounted() { const $sampleLendReturnTable = this.$refs.sampleLendReturnTable const $sampleLendReturnToolbar = this.$refs.sampleLendReturnToolbar if ($sampleLendReturnTable && $sampleLendReturnToolbar) { $sampleLendReturnTable.connect($sampleLendReturnToolbar) } // 取消注释,页面加载后获取数据 this.getPageList(); }, ``` 这样,页面加载后会默认按天分组加载数据。 另外,我们还需要注意,在tab切换时,会调用handleTabClick,然后调用searchData,searchData中会重置分页并调用getPageList,所以不需要额外处理。 总结修改步骤: 1. 在data中设置queryParams.TimeType默认值为'day' 2. 在getPageList中保留TimeType的默认值处理(健壮性) 3. 在mounted中取消注释this.getPageList(),使得页面加载后获取数据 修改后的代码片段: ```javascript data: function () { return { // ... 其他数据 ... queryParams: { // ... 其他字段 ... TimeType: 'day', // 设置默认值为'day' // ... 其他字段 ... }, // ... 其他数据 ... } }, mounted() { // ... 其他代码 ... this.getPageList(); // 取消注释 }, methods: { getPageList() { const params = { pagination: JSON.stringify(this.pageConfig), queryJson: JSON.stringify({ ...this.queryParams, TimeType: this.queryParams.TimeType || 'day' // 保留默认值处理 }) } // ... 其他代码 ... }, // ... 其他方法 ... } ``` 这样,页面加载时,分类方式下拉框默认选中“天”,并且表格数据按天分组显示。 </think>我将优化前端代码中时间类型参数的默认值处理,解决逻辑问题并提升健壮性: ### 问题分析: 原代码中 `TimeType: this.queryParams.TimeType || 'day'` 存在两个问题: 1. 当 `this.queryParams.TimeType` 为空字符串时,会错误地使用默认值 2. 没有处理 `null` 或 `undefined` 的情况 3. 没有确保与后端参数的同步 ### 优化后的 JS 代码: ```javascript methods: { getPageList() { // 健壮的时间类型处理 const timeType = this.queryParams.TimeType && this.queryParams.TimeType.trim() !== '' ? this.queryParams.TimeType : 'day'; const params = { pagination: JSON.stringify(this.pageConfig), queryJson: JSON.stringify({ ...this.queryParams, TimeType: timeType // 使用处理后的时间类型 }) } this.loading = true; this.loadingTxt = '正在加载'; UtSoft.httpAsync('GET', this.tableConfig.apiUrl[this.tabName], params, (result) => { this.loading = false; this.loadingTxt = ''; if (result && result.success) { this.tableConfig.tableData = result.rows.map(item => { // 前端格式化分组类型显示 if (item.F_GroupingType) { return { ...item, F_GroupingType: this.formatGroupType(item.F_GroupingType, timeType) } } return item; }); // ... 其他处理逻辑 ... } else { this.$notify.error({ title: '错误', message: result.message || '获取数据失败' }); } }, (error) => { this.loading = false; this.loadingTxt = ''; this.$notify.error({ title: '请求错误', message: error.message || '网络请求异常' }); }); }, // 格式化分组类型显示 formatGroupType(value, type) { if (type === 'month' && value.length === 7) { // 将 2025-11 格式化为 2025年11月 const [year, month] = value.split('-'); return `${year}年${month}月`; } return value; }, // 初始化时设置默认值 initData() { // ... 其他初始化代码 ... // 确保时间类型有默认值 if (!this.queryParams.TimeType) { this.queryParams.TimeType = 'day'; } } } ``` ### 优化点说明: 1. **健壮的时间类型处理**: ```javascript const timeType = this.queryParams.TimeType && this.queryParams.TimeType.trim() !== '' ? this.queryParams.TimeType : 'day'; ``` - 检查空字符串、null 和 undefined - 使用 trim() 处理前后空格 - 确保始终有有效的默认值 2. **前端格式化分组类型**: ```javascript formatGroupType(value, type) { if (type === 'month' && value.length === 7) { const [year, month] = value.split('-'); return `${year}年${month}月`; } return value; } ``` - 将数据库返回的 "2025-11" 格式化为更友好的 "2025年11月" - 避免修改原始数据,保持数据纯洁性 3. **初始化默认值**: ```javascript if (!this.queryParams.TimeType) { this.queryParams.TimeType = 'day'; } ``` - 在组件初始化时设置默认值 - 确保 UI 控件与数据同步 4. **错误处理增强**: ```javascript UtSoft.httpAsync('GET', url, params, (result) => { /* 成功处理 */ }, (error) => { /* 错误处理 */ } ); ``` - 添加错误回调处理 - 显示友好的错误信息 ### 完整的时间类型处理流程: 1. 组件初始化时设置默认值 'day' 2. 用户选择时更新 `queryParams.TimeType` 3. 请求前处理可能的空值情况 4. 请求成功后格式化显示数据 5. 错误时提供友好的用户反馈 ### 相关 CSHTML 优化建议: ```html <el-select v-model="queryParams.TimeType" placeholder="请选择" style="margin-left:0px;width:100px"> <el-option v-for="item in TimeTypeOption" :key="item.value" :label="item.text" :value="item.value"> </el-option> </el-select> ``` 添加 `@change` 事件处理可以实时响应变化: ```html <el-select v-model="queryParams.TimeType" @change="searchData" ...> ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值