306 1 分鐘

# 思路 動態規劃 dp[0] 與 dp[1] 為 1 之後 dp[i] 的方法數為 dp[i - 1] + dp[i - 2] # 參考程式碼 static auto fast_io = []{ ios::sync_with_stdio(false); cout.tie(nullptr); cin.tie(nullptr); return 0;}();class Solution {public: int climbStairs(int n) { int dp[n + 1]; dp[0] = dp[1] = 1; for...
192 1 分鐘

# 思路 開根號 # 參考程式碼 static auto fast_io = []{ ios::sync_with_stdio(false); cout.tie(nullptr); cin.tie(nullptr); return 0;}();class Solution {public: int mySqrt(int x) { return sqrt(x); }};
555 1 分鐘

# 思路 以另一個變數 ret 儲存 a + b 的值,並處理進位 # 參考程式碼 static auto fast_io = []{ ios::sync_with_stdio(false); cout.tie(nullptr); cin.tie(nullptr); return 0;}();class Solution {public: string addBinary(string a, string b) { reverse(a.begin(), a.end()); reverse(b.begin(),...
468 1 分鐘

# 思路 將 vector 最後 +1 需要一路往前處理進位 # 參考程式碼 static auto fast_io = []{ ios::sync_with_stdio(false); cout.tie(nullptr); cin.tie(nullptr); return 0;}();class Solution {public: vector<int> plusOne(vector<int>& digits) { ++digits[digits.size() -...
268 1 分鐘

# 思路 以 stringstream 拆分字串 # 參考程式碼 static auto fast_io = []{ ios::sync_with_stdio(false); cout.tie(nullptr); cin.tie(nullptr); return 0;}();class Solution {public: int lengthOfLastWord(string s) { string word; stringstream ss(s); while(ss >> word) ; return...
355 1 分鐘

# 思路 以 cur 紀錄目前遍歷的最大值 以 ret 紀錄全部的最大值 # 參考程式碼 static auto fast_io = []{ ios::sync_with_stdio(false); cout.tie(nullptr); cin.tie(nullptr); return 0;}();class Solution {public: int maxSubArray(vector<int>& nums) { int ret = nums[0]; int cur =...
315 1 分鐘

# 思路 直接調用 lower_bound 找到位置,再減去 nums.begin() 得到位置的整數 # 參考程式碼 static auto fast_io = []{ ios::sync_with_stdio(false); cout.tie(nullptr); cin.tie(nullptr); return 0;}();class Solution {public: int searchInsert(vector<int>& nums, int target) { return...
430 1 分鐘

# 思路 先記錄 haystack 與 needle 的 size 從 0 開始依序比對 haystack 的 sub string 與 needle # 參考程式碼 static auto fast_io = []{ ios::sync_with_stdio(false); cout.tie(nullptr); cin.tie(nullptr); return 0;}();class Solution {public: int strStr(string haystack, string needle) { int...
327 1 分鐘

# 思路 以 i 紀錄位置,依序遍歷 # 參考程式碼 static auto fast_io = []{ ios::sync_with_stdio(false); cout.tie(nullptr); cin.tie(nullptr); return 0;}();class Solution {public: int removeElement(vector<int>& nums, int val) { if (!nums.size()) return 0; int i = -1;...
310 1 分鐘

# 思路 以變數 i 控制儲存位置,直接覆蓋重複的值 # 參考程式碼 static auto fast_io = []{ ios::sync_with_stdio(false); cout.tie(nullptr); cin.tie(nullptr); return 0;}();class Solution {public: int removeDuplicates(vector<int>& nums) { int i = 0; for (int j = 0; j <...