zoukankan      html  css  js  c++  java
  • Leetcode 本地IDE调试的一些心得

    有些刚开始刷Leetcode的朋友 往往在遇到wa提示不能正确解答问题的时候,仅靠添加打印来debug会比较吃力。

    这时候希望能够将代码在本地运行,单步调试,以便提升debug的效率。

    1 常规题目

    使用本地的C++编译执行工具。
    添加头文件 添加Leetcode的类 和 main函数 调用该类,并且输入数据
    Leetcode 1 两数之和 为例

    这里的输出不正确,那么我们在本地的代码应该如下:

    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    class Solution {
    public:
    	vector<int> twoSum(vector<int>& nums, int target) {
    		for (int i = 0; i < nums.size(); i++) {
    			for (int j = i + 1; j < nums.size(); j++) {
    				if (nums[i] + nums[j] == target) {
    					return vector<int>{i, j};
    				}
    			}
    		}
    
    		return vector<int>();
    	}
    };
    
    int main()
    {
    	//main函数中新建一个类 ,并且调用该类的函数, 
    	Solution s;
    	//输入的数据要根据网页提示 自行创建
    	vector<int> v{ 2,7,11,15 };
    	s.twoSum(v,9);
    
    	return 0;
    }
    

    这样就可以在本地单步调试代码,更优效率的定位BUG,对算法代码也能理解的更加深入.
    如图

    2 链表题目

    链表题目的本地调试和常规题目类似,但是数据的创建会稍微麻烦一些
    需要实现声明数据结构的定义并且 自行创建一个链表,相比输入vector数据会更麻烦一些
    Leetcode 83 删除排序链表中的重复元素 为例
    输入的链表数据是 1->1->2

    本地代码应该如下

    #include <iostream>
    #include <vector>
    
    using namespace std;
    
     // Definition for singly-linked list.
    //定义链表结构体 
      struct ListNode {
          int val;
          ListNode *next;
          ListNode() : val(0), next(nullptr) {}
          ListNode(int x) : val(x), next(nullptr) {}
          ListNode(int x, ListNode *next) : val(x), next(next) {}
      };
     
    class Solution {
    public:
    	ListNode* deleteDuplicates(ListNode* head) {
    		if (!head) {
    			return head;
    		}
    
    		ListNode* cur = head;
    		while (cur->next) {
    			if (cur->val == cur->next->val) {
    				cur->next = cur->next->next;
    			}
    			else {
    				cur = cur->next;
    			}
    		}
    
    		return head;
    	}
    };
    
    int main()
    {
    	//创建类 调用函数 
    	Solution s;
    	//自行创建输入的链表数据
    	ListNode* head = new ListNode(1);
    	head->next = new ListNode(1);
    	head->next->next = new ListNode(2);
    
    	s.deleteDuplicates(head);
    
    	return 0;
    }
    

    就可以开始本地单步调试代码了。
    二叉树的题目与链表题目类似。

    附注
    因为写OJ题目应该尽量远离代码,人脑调试定位和走流程才是吸收效率最高的。
    如果入门后,建议大家尽量避免使用打印以外的调试方式,学习才更有效率。

    我的视频题解空间

    作 者: itdef
    欢迎转帖 请保持文本完整并注明出处
    技术博客 http://www.cnblogs.com/itdef/
    B站算法视频题解
    https://space.bilibili.com/18508846
    qq 151435887
    gitee https://gitee.com/def/
    欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    mysql数据库分区功能及实例详解
    Mysql线程池优化笔记
    mariadb multi-source replication(mariadb多主复制)
    mysql---二进制日志
    MySQL binlog_format (Mixed,Statement,Row)[转]
    如何生成唯一的server Id,server_id为何不能重复?
    mysql复制过程中的server-id的理解
    MySQL参数:innodb_flush_log_at_trx_commit 和 sync_binlog
    Mysql 用户和权限管理
    B+树索引和哈希索引的区别[转]
  • 原文地址:https://www.cnblogs.com/itdef/p/15353465.html
Copyright © 2011-2022 走看看