Source
力扣LeetCode题库
App > LeetCode > 题库 > 题解
Notes
- 仔细审题,明确输入输出,通过测试用例。
- 先特殊,后寻常。
- 逆向思维。
- 在条件语句中用
!=
代替==
,提前终止循环,减少嵌套层级(else)
Debug环境
- VSCode > Extensions > LeetCode > Install
- Leecode > Show Problem / Show Top Voted Solution / Code Now
- Explorer > Code > Test | Submit
默认功能只允许测试和提交 - Explorer > Debug
准备Debug环境
-
在launch.json文件中配置java环境
-
创建一个主类test.java
-
对应测试题Solution类改为S类,主类test.java中main函数中调用S()中的方法(避免多题Solution类冲突。同时记得测试完的题目中S类修改回Solution类)
-
Run and Debug > Debug ▶️(左上角)
Refer to bli-video: How to set leetcode debug environment in vsCode
Note: Debug leetcode extension supports python, js…
背景-为什么要创建DeBug环境?
LeetCode官方DeBug环境需要升级账户使用。
如何创建DeBug环境?
Easy
1. Two Sum
class Solution { // 定义一个名为Solution的类public int[] twoSum(int[] nums, int target) {int n = nums.length;for (int i = 0; i < n; ++i) {for (int j = i + 1; j < n; ++j) {if (nums[i] + nums[j] == target) {return new int[]{i, j};}}}return new int[0];}
}
9. Palindrome Number
Palindrome Number (回文数): A number that reads the same backward as forward.
Thoughts
- 将int转换为string需要额外非常量空间,优先考虑其他方式(进阶)
- -231 <= x <= 231-1 (int range): 反转可能溢出,反转一半数字
class Solution {public boolean isPalindrome(int x) {if (x < 0 || (x % 10 == 0 && x != 0)) {return false;}int revertedNumber = 0;while (x > revertedNumber) {revertedNumber = revertedNumber * 10 + x % 10;x /= 10;}return x == revertedNumber || x == revertedNumber / 10;}
}
13. Rome to Integer
The key intuition lies in the fact that in Roman numerals, when a smaller value appears before a larger value, it represents subtraction, while when a smaller value appears after or equal to a larger value, it represents addition.
class Solution {public int romanToInt(String s) {Map<Character, Integer> m = new HashMap<>();m.put('I', 1);m.put('V', 5);m.put('X', 10);m.put('L', 50);m.put('C', 100);m.put('D', 500);m.put('M', 1000);int ans = 0;for (int i = 0; i < s.length(); i++) {if (i < s.length() - 1 && m.get(s.charAt(i)) < m.get(s.charAt(i + 1))) {ans -= m.get(s.charAt(i));} else {ans += m.get(s.charAt(i));}}return ans;}
}
14. Longest Common Prefix
To find the longest common prefix, first sort the list lexicographically(字典序/字母序:基于Unicode编码/ASCII值). The longest common prefix will always be the shared prefix between the first and last strings in the sorted list. This works because if the lexicographically smallest string (‘flight’) and largest string (‘flower’) share a prefix, all middle strings must share that prefix too.
class Solution {public String longestCommonPrefix(String[] strs) {StringBuilder ans = new StringBuilder();Arrays.sort(strs); String first = strs[0], last = strs[strs.length-1]; for (int i = 0; i < Math.min(first.length(), last.length()); i++) {if (first.charAt(i) == last.charAt(i)) {ans.append(first.charAt(i));}return ans.toString();}return ans.toString();}
}