Leetcode题解
文章平均质量分 63
zhaobaoxue
这个作者很懒,什么都没留下…
展开
-
Valid Palindrome
class Solution {public: bool isPalindrome(string s) { int len = s.length(); if(len == 0) return true; transform(s.begin(), s.end(), s.begin()转载 2014-03-06 18:23:59 · 600 阅读 · 0 评论 -
Add Binary
将两个输入字符串逆置,从最低位到最高位进行相加,并处理进位情况。class Solution {public: string addBinary(string a, string b) { string result; reverse(a.begin(), a.end()); reverse(b.begin(转载 2014-03-06 19:51:13 · 465 阅读 · 0 评论 -
Symmetric Tree
方法一,使用递归,时间O(n),空间O(logN)。代码如下:class Solution {public: bool isSymmetric(TreeNode *root) { if(root == NULL) return true; else return isSymmetric(root->left, root->rig转载 2014-03-12 16:09:27 · 472 阅读 · 0 评论 -
Flatten Binary Tree to Linked List
迭代,使用前序遍历的思路。代码如下。class Solution {public: void flatten(TreeNode *root) { if(!root) return; stack s; s.push(root); TreeNode *cur, *prev = NULL;转载 2014-03-12 17:06:08 · 449 阅读 · 0 评论 -
Same Tree
方法一,递归,时间O(n),空间O(logN)。代码如下:class Solution {public: bool isSameTree(TreeNode *p, TreeNode *q) { if(!p && !q) return true; if(!p || !q) return false; retur转载 2014-03-12 12:56:14 · 318 阅读 · 0 评论 -
Evaluate Reverse Polish Notation
后缀表达式求解,使用栈,时间复杂度O(n),空间复杂度O(logn) (why?)代码如下:class Solution {public: int evalRPN(vector &tokens) { stack s; for(int i=0; i<tokens.size(); i++) {转载 2014-03-07 16:38:52 · 500 阅读 · 0 评论 -
Unique Binary Search Trees II
思路和上一题“Unique Binary Search Trees”一样,复杂度待求。代码如下:class Solution {public: vector generateTrees(int n) { return generate(1, n); } vector generate(int start, int end) {转载 2014-03-13 10:28:06 · 445 阅读 · 0 评论 -
Convert Sorted Array to Binary Search Tree
递归法。时间O(n),空间O(logN)。class Solution {public: TreeNode *sortedArrayToBST(vector &num) { return convert(num, 0, num.size()); } TreeNode *convert(vector &num, int start, int l原创 2014-03-13 11:24:57 · 383 阅读 · 0 评论 -
Convert Sorted List to Binary Search Tree
参考:http://leetcode.com/2010/11/convert-sorted-list-to-balanced-binary.html方法一,自顶向下,与 Convert Sorted Array to Balanced Binary Search Tree (BST) 相同。由于list不能随机访问,因此找到mid元素必须遍历半个list,时间复杂度为O(nlogn)。转载 2014-03-13 12:24:43 · 752 阅读 · 0 评论 -
Valid Parentheses
时间复杂度和空间复杂度均为O(n)class Solution {public: bool isValid(string s) { const int n = s.size(); if(n == 0) return true; string left = "({[";转载 2014-03-07 11:59:43 · 504 阅读 · 0 评论 -
Longest Substring Without Repeating Characters
方法一: 用一个int a[256] 标记每一个字符最后一次出现的位置,将数组a的各个变量初始化位-1。 代码如下:class Solution {public: int lengthOfLongestSubstring(string s) { int a[256]; memset(a, -1, sizeof(a));原创 2014-03-17 22:15:07 · 427 阅读 · 0 评论 -
Surrounded Regions
Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.A region is captured by flipping all 'O's into 'X's in that surrounded region.For example,X X X XX O O X转载 2014-04-14 16:56:34 · 380 阅读 · 0 评论 -
Longest Consecutive Sequence
使用hash set,首先将数组中的所有元素添加到set中,然后针对数组中的每一个元素进行查找:如果该元素在set中,则从该元素向左右扫描,从set中移除最长的连续序列,并记录长度。直到碰到不连续为止。代码如下:class Solution {public: int longestConsecutive(vector &num) { unorde转载 2014-03-30 16:11:49 · 453 阅读 · 0 评论 -
Pascal's Triangle II
一层层计算,class Solution {public: vector getRow(int rowIndex) { vector result; result.push_back(1); while(rowIndex > 0) { for(int i=result.size()-1; i>0;原创 2014-04-14 23:08:34 · 381 阅读 · 0 评论 -
Best Time to Buy and Sell Stock III
DP算法。参考http://blog.csdn.net/fightforyourdream/article/details/14503469转载 2014-04-14 22:48:59 · 435 阅读 · 0 评论 -
4Sum
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.Note:Elements转载 2014-03-30 15:03:48 · 397 阅读 · 0 评论 -
Merge Sorted Array
从后往前merge。时间O(n),空间O(1)。class Solution {public: void merge(int A[], int m, int B[], int n) { int i = m-1, j=n-1, k=m+n-1; while(i>=0 && j>=0) { if(A原创 2014-03-21 11:22:51 · 410 阅读 · 0 评论 -
Merge Two Sorted Lists
从前往后Merge,时间O(1),空间O(n)。代码如下:class Solution {public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { ListNode dummy(-1); ListNode *cur = &dummy; while(l原创 2014-03-21 11:40:47 · 362 阅读 · 0 评论 -
Median of Two Sorted Arrays
解法参考: http://blog.csdn.net/ojshilu/article/details/15027309代码如下:class Solution {public: double findMedianSortedArrays(int A[], int m, int B[], int n) { int total = m+n; if(tot转载 2014-04-03 11:57:01 · 368 阅读 · 0 评论 -
Add Two Numbers
注意最后一个进位如果不为0,则需要增加一个节点。class Solution {public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode dummy(-1); ListNode *cur = &dummy; int carry = 0;原创 2014-04-03 12:32:48 · 348 阅读 · 0 评论 -
Linked List Cycle
使用快慢指针,如果两个指针在遍历的过程中相遇,则链表有环,否则无环。class Solution {public: bool hasCycle(ListNode *head) { ListNode *fast = head, *slow = head; while(fast && fast->next) {转载 2014-03-24 10:58:20 · 400 阅读 · 0 评论 -
Linked List Cycle II
使用快慢指针slow和fast,如果有环,slow和fast必然相遇。设此时slow指针走了x步,环的长度为y,链表总长度位L。则 2x = x + ny,即快指针已经围绕环转了n圈。设表头距离环开始位置的距离位t,环开始位置距离相遇位置a,则a+t = x。x = ny =>x = (n-1)y + y, =>a + t = (n-1)y + y, =>t = (n-1转载 2014-03-24 11:34:23 · 374 阅读 · 0 评论 -
Remove Nth Node From End of List
class Solution {public: ListNode *removeNthFromEnd(ListNode *head, int n) { if(head == NULL) return head; //be careful when there is only one node and delete it.原创 2014-03-24 16:30:41 · 331 阅读 · 0 评论 -
LRU Cache
细节实现题,使用一个双向链表std::list和一个hash表实现O(1)时间内对节点的访问,有保证了节点的有序性(记录最后被访问的先后顺序)。需要注意实现的细节,多练习。class LRUCache{public: struct CacheNode { int key; int value; CacheNode(int k,转载 2014-03-24 10:53:11 · 373 阅读 · 0 评论 -
Swap Nodes in Pairs
两个两个地交换,时间O(n),空间O(1)。class Solution {public: ListNode *swapPairs(ListNode *head) { if(head == NULL || head->next == NULL) return head; ListNode dummy(-1);原创 2014-03-24 16:07:08 · 443 阅读 · 0 评论 -
Two Sum
方法一,暴力搜索,时间O(n^2)。方法二,使用hash (可用STL中的unordered_map)来保存每个int对应的index,时间O(n),空间O(n)。代码如下:class Solution {public: vector twoSum(vector &numbers, int target) { vector result; unor转载 2014-03-24 19:53:04 · 391 阅读 · 0 评论 -
Gas Station
从头往后扫描,时间O(n),空间O91转载 2014-04-03 22:24:22 · 405 阅读 · 0 评论 -
Set Matrix Zeroes
利用第一行和第一列做标记,事先转载 2014-04-03 23:04:10 · 394 阅读 · 0 评论 -
Trapping Rain Water
建立一个数组num,表示当前位置的水平高度(包括水和bar之和)。第一个位置num[0]和最后一个位置num[n-1]因为是开区间,肯定不能trap water。从第二个位置num[1]开始往后扫描,如果num[i]取num[i-1]和A[i]的较大者。表示该位置水平高度的上限(尚未考虑右侧邻居)。然后从倒数第二个位置开始往前扫描,保证num[i] 每个位置trap的水量即为num[i原创 2014-04-03 21:47:12 · 360 阅读 · 0 评论 -
Unique Paths
方法一:DP+滚动数组。时间O(n^2),空间O(n)。转载 2014-04-07 11:23:08 · 429 阅读 · 0 评论 -
Jump Game
Given an array of non-negative integers, you are initially positioned at the first index of the array.Each element in the array represents your maximum jump length at that position.Determine i转载 2014-04-07 23:17:56 · 441 阅读 · 0 评论 -
Pow(x, n)
Implement pow(x, n).二分法。时间O(转载 2014-04-07 20:26:03 · 440 阅读 · 0 评论 -
Container With Most Water
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Fin原创 2014-04-08 20:25:39 · 406 阅读 · 0 评论 -
Triangle
动态规划问题,从最下层一直向上一层一层相加,对于每个元素,原创 2014-04-08 20:49:56 · 362 阅读 · 0 评论 -
Sort List
使用Merge Sort。开始的是后/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {publ原创 2014-04-12 11:34:50 · 401 阅读 · 0 评论 -
Word Break II
使用二位bool数组来标记前去vector table[n+1];class Solution {public: vector wordBreak(string s, unordered_set &dict) { const int n = s.size(); vector table[n+1]; for(int i=1; i<=n;原创 2014-04-12 22:52:35 · 555 阅读 · 0 评论 -
Minimum Window Substring
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).For example,S = "ADOBECODEBANC"T = "ABC"Minimum window is "BAN原创 2014-05-29 18:54:25 · 386 阅读 · 0 评论 -
Multiply Strings
参考:http://fisherlei.blogspot.hk/2012/12/leetcode-multiply-strings.html转载 2014-05-29 21:14:22 · 364 阅读 · 0 评论 -
Permutations
方法一,先对利用next_permutation算法原创 2014-04-06 16:00:46 · 437 阅读 · 0 评论 -
Combinations
深度递归,时间复杂度O(n!),空间O(n)。class Solution {public: vector > combine(int n, int k) { vector > result; vector path; dfs(n,k,1,0, path, result); return result;转载 2014-03-30 14:02:00 · 401 阅读 · 0 评论