From be2b464cd30259c4dd4aba60f5e1c0e7793ac823 Mon Sep 17 00:00:00 2001 From: Qinghao Dai Date: Thu, 16 Jul 2015 22:26:06 -0700 Subject: [PATCH 1/2] Update bestTimeToBuyAndSellStock.cpp shorter version, with max and min function. --- .../bestTimeToBuyAndSellStock.cpp | 25 ++++--------------- 1 file changed, 5 insertions(+), 20 deletions(-) diff --git a/algorithms/bestTimeToBuyAndSellStock/bestTimeToBuyAndSellStock.cpp b/algorithms/bestTimeToBuyAndSellStock/bestTimeToBuyAndSellStock.cpp index e6bc986b1..f10321f86 100644 --- a/algorithms/bestTimeToBuyAndSellStock/bestTimeToBuyAndSellStock.cpp +++ b/algorithms/bestTimeToBuyAndSellStock/bestTimeToBuyAndSellStock.cpp @@ -25,28 +25,13 @@ class Solution { // Notes: // Some people think find the highest-price & lowest-price, this is wrong. // Because the highest-price must be after lowest-price - // int maxProfit(vector &prices) { - - int max=0, begin=0, end=0, delta=0; - + if(prices.size() == 0) return 0; + int MAX=0, MIN=prices[0]; for (int i=0; i max ){ - max = delta; - } - + MIN = min(MIN, prices[i]); + MAX = max(MAX, prices[i] - MIN); } - - return max; - + return MAX; } }; From f1d5a27e7b944dc2c7b4c0c2f206a0344e100833 Mon Sep 17 00:00:00 2001 From: Qinghao Dai Date: Thu, 16 Jul 2015 22:44:00 -0700 Subject: [PATCH 2/2] Update KthSmallestElementInABst.cpp remove nested while loop. --- .../KthSmallestElementInABst.cpp | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/algorithms/kthSmallestElementInaBST/KthSmallestElementInABst.cpp b/algorithms/kthSmallestElementInaBST/KthSmallestElementInABst.cpp index fd3581b50..15f450cb3 100644 --- a/algorithms/kthSmallestElementInaBST/KthSmallestElementInABst.cpp +++ b/algorithms/kthSmallestElementInaBST/KthSmallestElementInABst.cpp @@ -49,20 +49,17 @@ class Solution { // in-order travel - non-recursive way int kthSmallestHelper_nonRecursive(TreeNode* root, int k){ stack s; - while(!s.empty() || root){ - - while (root) { + if(root){ s.push(root); - root = root->left; + root = root -> left; + }else{ + root = s.top(); + s.pop(); + k--; + if(k==0) return root -> val; + root = root -> right; } - - k--; - root = s.top()->right; - - if (k==0) return s.top()->val; - - s.pop(); } return -1; }