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题目应该尽量远离代码,人脑调试定位和走流程才是吸收效率最高的。
如果入门后,建议大家尽量避免使用打印以外的调试方式,学习才更有效率。

我的视频题解空间

posted on   itdef  阅读(1576)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2020-09-29 LeetCode 679. 24 点游戏 dfs
2020-09-29 LeetCode 145. 二叉树的后序遍历

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示