54. Spiral Matrix

Description: https://leetcode.com/problems/spiral-matrix/#/description Algorithm: right->down->left->up After finishing each direction, check if break Code: class Solution {class Solution {public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> result; int rowLow = 0, colLow = 0, rowHigh = matrix.size() – 1, colHigh = matrix[0].size() – 1; while (true) { for (int i = colLow; i <= colHigh; i++) {  result.push_back(matrix[rowLow][i]); cout … Read more54. Spiral Matrix

53. Maximum Subarray

Description: https://leetcode.com/problems/maximum-subarray/#/description Algorithm: Use dp, if dp[i – 1] < 0, discard. if dp[i – 1] > 0, dp[i] = dp[i] + nums[i] Code: int maxSubArray(vector<int>& nums) { int maxSubArray(vector<int>& nums) { int n = nums.size(); vector<int> dp(n); dp[0] = nums[0]; int res = nums[0]; for (int i = 1; i < n; i++) { … Read more53. Maximum Subarray

26. Remove Duplicates from Sorted Array

Description: https://leetcode.com/problems/remove-duplicates-from-sorted-array/#/description Algorithm: Use swap. Code: class Solution { public:     int removeDuplicates(vector<int>& nums)    {         if (nums.size() == 0) return 0;         int length = 0;         for (int i = 0; i < nums.size(); i++) {         if (nums[length] … Read more26. Remove Duplicates from Sorted Array

41. First Missing Positive

Description: https://leetcode.com/problems/first-missing-positive/#/description Algorithm: I used unordered_map. Go through the array to record the max number and min number.   Code: class Solution { public: int firstMissingPositive(vector& nums) { unordered_map <int, int> mapping; int maxNum = 0; int minNum = INT_MAX; for (int i = 0; i < nums.size(); i++) { mapping[nums[i]] = 1; if (nums[i] … Read more41. First Missing Positive

34. Search for a Range

Description: https://leetcode.com/problems/search-for-a-range/#/description Algorithm: Use find() to determine whether the target is in the array. Left = 0, right = size – 1; Squeeze left and right to find middle s.t. nums[middle] == target Squeeze left and middle to find left s.t.  nums[left] == target Squeeze right and middle to find right s.t.  nums[right] == target … Read more34. Search for a Range

14. Longest Common Prefix

Description: 14. Longest Common Prefix Code: class Solution { public: string longestCommonPrefix(vector<string>& strs) { if (strs.size() == 0) return “”; if (strs.size() == 1) return strs[0]; string checked = strs[0]; int k = 0; bool ifEnd = false; string result = “”; while ( k < checked.size()) { for (int i = 1; i < … Read more14. Longest Common Prefix