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();}
}