有一個6升和一個5升的水桶,有一個無限大的水池,目標是得到3升水
(1) 6L裝滿 → (6L:6, 5L:0)
(2) 6L倒入5L → (6L:1, 5L:5)
(3) 5L清空 → (6L:1, 5L:0)
(4) 6L倒入5L → (6L:0, 5L:1)
(5) 6L裝滿 → (6L:6, 5L:1)
(6) 6L倒入5L → (6L:2, 5L:5)
(7) 5L清空 → (6L:2, 5L:0)
(8) 6L倒入5L → (6L:0, 5L:2)
(9) 6L裝滿 → (6L:6, 5L:2)
(10) 6L倒入5L → (6L:3, 5L:5)
LeetCode Plus One
class Solution {
public int[] plusOne(int[] digits) {
// 從最後一位開始
for (int i = digits.length - 1; i >= 0; i--) {
// 如果不是 9,則加 1 後返回
if (digits[i] != 9) {
digits[i]++;
return digits;
}
// 如果是 9,則設為 0 後繼續執行
digits[i] = 0;
}
// 執行到這表示皆為 9,則建立新陣列,長度 +1 且首位 +1
int[] newDigits = new int[digits.length + 1];
newDigits[0] = 1;
return newDigits;
}
}
Java 找最大公因數 (GCD)
// 方法一
class Solution {
public static void main(String[] args) {
BigInteger bigInteger1 = BigInteger.valueOf(48);
BigInteger bigInteger2 = BigInteger.valueOf(18);
System.out.println(bigInteger1.gcd(bigInteger2));
}
}
// 方法二
class Solution {
// GCD(a, b) = GCD(b, a mod b)
// 其中 a mod b 是 a 除以 𝑏 的餘數,當 b = 0 時,a 就是最大公因數。
public static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public static void main(String[] args) {
System.out.println(gcd(48, 18));
}
}
HTTP Request Method 知道哪幾個
GET: 用於獲取資源
POST: 用於提交數據
PUT: 用於更新資源
DELETE: 用於刪除資源
PATCH: 用於部分更新資源
HEAD: 類似GET,但只返回頭部信息
OPTIONS: 用於獲取目標資源支持的通信選項
更新單一欄位可能就會使用 PATCH
字元陣列是否為回文
class Solution {
public static boolean isPalindrome(char[] arr) {
int left = 0;
int right = arr.length - 1;
while (left < right) {
if (arr[left] != arr[right]) {
return false; // 若不相等,則不是回文
}
left++;
right--;
}
return true; // 若所有對應的字元相等,則是回文
}
public static void main(String[] args) {
char[] arr1 = {'a', 'b', 'c', 'b', 'a'};
}
}
RDBMS 四大特性
原子性 (Atomicity):完全執行,或完全不執行。
一致性 (Consistency):事務執行前後,資料庫保持一致狀態。
隔離性 (Isolation):併發事務互不干擾,各自獨立執行。
持久性 (Durability):一旦事務提交,結果永久保存。
同源政策 (Same-origin policy)
是瀏覽器的安全防護機制,規定網頁只能訪問「相同來源」的資源
一個源(Origin)由三個部分組成:協議、主機、端口
使用 CORS (Cross-Origin Resource Sharing) 解決同源政策
// 後端設置
res.setHeader('Access-Control-Allow-Origin', '*'); // 允許所有來源,但建議不要使用 *,應該明確指定允許的域名
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); // 允許的請求方法
res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); // 允許的請求頭