写在前面:
因为要准备面试,开始了在[LeetCode]上刷题的历程。
LeetCode上一共有大约150道题目,本文记录我在<http://oj.leetcode.com>上AC的所有题目,以Leetcode上AC率由高到低排序,基本上就是题目由易到难。我应该会每AC15题就过来发一篇文章,争取早日刷完。所以这个第二篇还是相对比较简单的15道题了。
部分答案有参考网上别人的代码,和leetcode论坛里的讨论,很多答案肯定有不完美的地方,欢迎提问,指正和讨论。
No.16
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
class Solution { public: int climbStairs(int n) { if(n==0) return 0; if(n==1) return 1; if(n==2) return 2; int A[n]; A[0] = 1; A[1] = 2; for(int i=2; i<n; i++) { A[i] = A[i-2] + A[i-1]; } return A[n-1]; } };
No.17
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
class Solution { public: int romanToInt(string s) { int result = 0; for(int i = 0; i<s.length(); i++) { switch (s[i]) { case 'I': { if((i+1) < s.length()){ switch (s[i+1]) { case 'V': result += 4; i++; break; case 'X': result += 9; i++; break; default: result += 1; } } else result += 1; } break; case 'X': { if((i+1)<s.length()){ switch (s[i+1]) { case 'L': result += 40; i++; break; case 'C': result += 90; i++; break; default: result += 10; } } else result += 10; } break; case 'C': { if((i+1)<s.length()){ switch(s[i+1]) { case 'D': result += 400; i++; break; case 'M': result += 900; i++; break; default: result += 100; } } else result += 100; } break; case 'V': result += 5; break; case 'L': result += 50; break; case 'M': result += 1000; break; case 'D': result += 500; break; } } return result; } };
No.17
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int help(TreeNode *left, TreeNode *right) { if(left==NULL&&right==NULL) return true; if(left==NULL||right==NULL) return false; if(left->val!=right->val) return false; return(help(left->left,right->right)&&help(left->right,right->left)); } bool isSymmetric(TreeNode *root) { if(!root) return true; return help(root->left,root->right); } };
No.18
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { if(!l1||!l2) return l1==NULL?l2:l1; ListNode *p = l1, *q = l2, *tmp = NULL,*tmp2 = NULL, *head=NULL; if(p->val<=q->val) head = p; else head = q; while(p&&q) { if(p->val<=q->val) { if(p->next) { tmp = p; p = p->next; continue; } else { p->next = q; return head; } } else { if(tmp) { tmp -> next = q; tmp2 = q; q = p; p = tmp2; } else { tmp2 = q; q = p; p = tmp2; } } } return head; } };
No.19
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void insert_Node(TreeNode* &p, int q) { if(!p) { //TreeNode *tmp =NULL; p = (TreeNode*)malloc(sizeof(struct TreeNode)); p->left = NULL; p->right = NULL; p->val = q; return; } if(q>p->val) insert_Node(p->right, q); else insert_Node(p->left, q); } void Insert(TreeNode* &p, vector<int> &num, int low, int high) { if(low>high) return; int mid = (low+high)/2; insert_Node(p,num[mid]); Insert(p, num, low, mid-1); Insert(p, num, mid+1, high); } TreeNode *sortedArrayToBST(vector<int> &num) { if(num.empty()) return NULL; TreeNode *root=NULL; //= (TreeNode*)malloc(sizeof(TreeNode)); int low = 0, high = num.size(); // int mid = (low + high)/2; Insert(root, num, low, high-1); return root; } };
No.20
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
class Solution { public: void merge(int A[], int m, int B[], int n) { if(!m&&n) { for(int i = 0; i<n; i++) A[i] = B[i]; } if(!n) return; int i = 0, j = 0, q = 0; while(i < m&&j < n && i+q<m+n) { if(A[i+q]<=B[j]) i++; else { for(int k=m+q;k>i+q;k--) { A[k]=A[k-1]; } A[i+q++] = B[j++]; } } if(i==m) { for(int k = 0; k+j<n; k++) { A[i+q+k] = B[j+k]; } } } };
No.21
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *swapPairs(ListNode *head) { if(!head) return NULL; if(!(head->next)) return head; ListNode *p = head, *q = head->next, *o = NULL, *tmp = NULL, *h = NULL; o = (ListNode*)malloc(sizeof(struct ListNode)); //tmp = (ListNode*)malloc(sizeof(struct ListNode)); o->next = p; int i = 0; bool flag = false; if(!(q->next)) { head = q; q -> next = p; p->next = NULL; return head; } while(q->next) { if(!(i%2)) { if(p==head) { p->next = q->next; q->next = p; head = q; //flag = true; } else { p->next = q->next; o->next = q; q->next = p; } tmp = p; p = q; q = tmp; } //if() o = p;//o->next; p = q;//p->next; q = q->next; i++; } if(!(i%2)) { p->next = NULL; o->next = q; q->next = p; } return head; } };
No.22
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
class Solution { public: vector<vector<int> > generate(int numRows) { vector<int> s,d; vector<vector<int>> r; s.push_back(1); d.push_back(1); d.push_back(1); if(!numRows) return r; r.push_back(s); if(numRows==1) return r; r.push_back(d); if(numRows==2) return r; int tmp = 0; for(int i = 2; i<numRows; i++) { if(!(i%2)) { s.clear(); s.push_back(1); for(int j = 0; j<i-1; j++) { tmp = d[j]+d[j+1]; s.push_back(tmp); } s.push_back(1); r.push_back(s); } if((i%2)) { d.clear(); d.push_back(1); for(int j = 0; j<i-1; j++) { tmp = s[j]+s[j+1]; d.push_back(tmp); } d.push_back(1); r.push_back(d); } } return r; } };
No.23
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
class Solution { public: int maxProfit(vector<int> &prices) { if(prices.size()<2) return 0; if(prices.size() == 2) return (prices[1]-prices[0])>0?(prices[1]-prices[0]):0; int low = prices[0], high = 0, result = 0, n = prices.size(), j = 0, tmp = 0; bool flag = false; for( int i = 1; i<n-1; i++ ) { while(prices[i+j]==prices[i+j+1]) j++; if(prices[i]>prices[i-1]&&prices[i]>prices[i+j+1]) { high = prices[i]; tmp = high-low; if(result<tmp) result = tmp; } if(prices[i]<prices[i-1]&&prices[i]<prices[i+j+1]) { if(low>prices[i]) low = prices[i]; } i += j; j = 0; } if(prices[n-1]>prices[n-2]&&prices[n-1]>low) { tmp = prices[n-1] - low; if(result<tmp) result = tmp; } return result; } };
No.24
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: static int tree_height(const TreeNode* root, bool& balanced) { const int left_height = root->left ? tree_height(root->left, balanced) + 1 : 0; if (!balanced) return 0; const int right_height = root->right ? tree_height(root->right, balanced) + 1 : 0; if (!balanced) return 0; const int diff = left_height - right_height; if (diff < -1 || diff > 1) balanced = false; return (left_height > right_height ? left_height : right_height); } bool isBalanced(TreeNode *root) { bool balanced = true; if (root) tree_height(root, balanced); return balanced; } };
No.25
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
class Solution { public: string intToRoman(int num) { string s; s.clear(); while(num) { if(num>=1000) { s += "M"; num -= 1000; continue; } else if(num>=900) { s += "CM"; num -= 900; continue; } else if(num>=500) { s += "D"; num -= 500; continue; } else if(num>=400) { s += "CD"; num -= 400; continue; } else if(num>=100) { s += "C"; num -= 100; continue; } else if(num>=90) { s += "XC"; num -= 90; continue; } else if(num>=50) { s += "L"; num -= 50; continue; } else if(num>=40) { s += "XL"; num -= 40; continue; } else if(num>=10) { s += "X"; num -= 10; continue; } else if(num>=9) { s +="IX"; num -= 9; continue; } else if(num>=5) { s +="V"; num -= 5; continue; } else if(num>=4) { s +="IV"; num -= 4; continue; } else if(num>=1) { s +="I"; num -= 1; continue; } } return s; } };
No.26
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
class Solution { public: int singleNumber(int A[], int n) { int count[32] = {0}; int result = 0; for(int i = 0; i < n; i++) { for(int j = 0; j<32; j++) { if((A[i]>>j)&1) count[j]++; if(!(count[j]%3)) count[j] = 0; } } for(int i = 0; i<32; i++) { result += (count[i]<<i); } return result; } };
No.27
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7] [9,20], [3], ]
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: vector<vector<int>> r; vector<int> t; public: int getDepth(TreeNode *root) { if(!root) return 0; int leftDepth = getDepth(root->left); int rightDepth = getDepth(root->right); return leftDepth>rightDepth?(leftDepth+1):(rightDepth+1); } void helper(TreeNode *root, int level) { if(!root||level<0) return; if(!level) t.push_back(root->val); helper(root->left, level-1); helper(root->right, level-1); } vector<vector<int> > levelOrderBottom(TreeNode *root) { r.clear(); t.clear(); if(!root) return r; int depth = getDepth(root); for(int i = depth - 1; i>-1; i--) { helper(root,i); r.push_back(t); t.clear(); } return r; } };
未完待续...