随笔- 509
文章- 0
评论- 151
阅读-
22万
12 2013 档案
LeetCode - Same Tree
摘要:Same Tree2013.12.31 22:56Given two binary trees, write a function to check if they are equal or not.Two binary trees are considered equal if they are structurally identical and the nodes have the same value.Solution: Check the root, the left subtree and the right subtree, recursively. That's the
阅读全文
LeetCode - Recover Binary Search Tree
摘要:Recover Binary Search Tree2013.12.31 19:00Two elements of a binary search tree (BST) are swapped by mistake.Recover the tree without changing its structure.Note:A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?confused what"{1,#,2,3}"means?
阅读全文
LeetCode - Validate Binary Search Tree
摘要:Validate Binary Search Tree2013.12.31 18:48Given a binary tree, determine if it is a valid binary search tree (BST).Assume a BST is defined as follows:The left subtree of a node contains only nodes with keysless thanthe node's key.The right subtree of a node contains only nodes with keysgreater
阅读全文
LeetCode - Unique Binary Search Trees
摘要:Unique Binary Search Trees2013.12.31 18:37Givenn, how many structurally uniqueBST's(binary search trees) that store values 1...n?For example,Givenn= 3, there are a total of 5 unique BST's. 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / ...
阅读全文
LeetCode - Binary Tree Inorder Traversal
摘要:Binary Tree Inorder Traversal2013.12.31 18:26Given a binary tree, return theinordertraversal of its nodes' values.For example:Given binary tree{1,#,2,3}, 1 \ 2 / 3return[1,3,2].Note:Recursive solution is trivial, could you do it iteratively?confused what"{1,#,2,3}"means?> read more
阅读全文
LeetCode - Restore IP Addresses
摘要:Restore IP Addresses2013.12.31 18:06Given a string containing only digits, restore it by returning all possible valid IP address combinations.For example:Given"25525511135",return["255.255.11.135", "255.255.111.35"]. (Order does not matter)Solution: Given a number strin
阅读全文
LeetCode - Reverse Linked List II
摘要:Reverse Linked List II2013.12.31 16:00Reverse a linked list from positionmton. Do it in-place and in one-pass.For example:Given1->2->3->4->5->NULL,m= 2 andn= 4,return1->4->3->2->5->NULL.Note:Givenm,nsatisfy the following condition:1 ≤m≤n≤ length of list.Solution1: Rever
阅读全文
LeetCode - Subsets II
摘要:Subsets II2013.12.27 02:47Given a collection of integers that might contain duplicates,S, return all possible subsets.Note:Elements in a subset must be in non-descending order.The solution set must not contain duplicate subsets.For example,IfS=[1,2,2], a solution is:[ [2], [1], [1,2,2], [2,2], ...
阅读全文
LeetCode - Decode Ways
摘要:Decode Ways2013.12.27 02:32A message containing letters fromA-Zis being encoded to numbers using the following mapping:'A' -> 1'B' -> 2...'Z' -> 26Given an encoded message containing digits, determine the total number of ways to decode it.For example,Given encoded me
阅读全文
LeetCode - Gray Code
摘要:Gray Code2013.12.27The gray code is a binary numeral system where two successive values differ in only one bit.Given a non-negative integernrepresenting the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.For example, givenn= 2, return[0,1,3,
阅读全文
LeetCode - Merge Sorted Array
摘要:Merge Sorted Array2013.12.27 01:18Given 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 aremandnrespectively.Solution1: First solution is simple and fo.
阅读全文
LeetCode - Partition List
摘要:Partition List2013.12.26 22:58Given a linked list and a valuex, partition it such that all nodes less thanxcome before nodes greater than or equal tox.You should preserve the original relative order of the nodes in each of the two partitions.For example,Given1->4->3->2->5->2andx= 3,re
阅读全文
LeetCode - Remove Duplicates from Sorted List II
摘要:Remove Duplicates from Sorted List II2013.12.26 21:42Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onlydistinctnumbers from the original list.For example,Given1->2->3->3->4->4->5, return1->2->5.Given1->1->1->2->3, return2->3.
阅读全文
LeetCode - Remove Duplicates from Sorted List
摘要:Remove Duplicates from Sorted List2013.12.26 21:36Given a sorted linked list, delete all duplicates such that each element appear onlyonce.For example,Given1->1->2, return1->2.Given1->1->2->3->3, return1->2->3.Solution: Removing the duplicates from a list requires two poin
阅读全文
LeetCode - Search in Rotated Sorted Array II
摘要:Search in Rotated Sorted Array II2013.12.26 20:07Follow up for "Search in Rotated Sorted Array":What ifduplicatesare allowed?Would this affect the run-time complexity? How and why?Write a function to determine if a given target is in the array.Solution1: First comes the link to the old ori
阅读全文
LeetCode - Remove Duplicates from Sorted Array II
摘要:Remove Duplicates from Sorted Array II2013.12.26 15:28Follow up for "Remove Duplicates":What if duplicates are allowed at mosttwice?For example,Given sorted array A =[1,1,1,2,2,3],Your function should return length =5, and A is now[1,1,2,2,3].Solution: We've done the problem "Remo
阅读全文
LeetCode - Subsets
摘要:Subsets2013.12.26 15:19Given a set of distinct integers,S, return all possible subsets.Note:Elements in a subset must be in non-descending order.The solution set must not contain duplicate subsets.For example,IfS=[1,2,3], a solution is:[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], []]Soluti...
阅读全文
LeetCode - Combinations
摘要:Combinations2013.12.22 05:17Given two integersnandk, return all possible combinations ofknumbers out of 1 ...n.For example,Ifn= 4 andk= 2, a solution is:[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4],]Solution: Combination and permutation problems are usually solved with DFS recursion. When solv...
阅读全文
LeetCode - Sort Colors
摘要:Sort Colors2013.12.22 04:39Given an array withnobjects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.Note:You a
阅读全文
LeetCode - Search a 2D Matrix
摘要:Search a 2D Matrix2013.12.22 04:30Write an efficient algorithm that searches for a value in anmxnmatrix. This matrix has the following properties:Integers in each row are sorted from left to right.The first integer of each row is greater than the last integer of the previous row.For example,Consider
阅读全文
LeetCode - Simplify Path
摘要:Simplify Path2013.12.22 04:19Given an absolute path for a file (Unix-style), simplify it.For example,path="/home/", =>"/home"path="/a/./b/../../c/", =>"/c"click to show corner cases.Corner Cases:Did you consider the case wherepath="/../"?In thi
阅读全文
LeetCode - Climbing Stairs
摘要:Climbing Stairs2013.12.22 04:13You are climbing a stair case. It takesnsteps 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?Solution: Search for "Fibonacci sequence" and calculate the nth element in the sequence. Time com
阅读全文
LeetCode - Sqrt(x)
摘要:Sqrt(x)2013.12.22 04:02Implementint sqrt(int x).Compute and return the square root ofx.Solution 1: The square root can be calculated using a binary iteration, with an initial interval of [1, x - 1]. Time complexity is O(log2(x)), space complexity is O(1).Accepted code: 1 // 2WA, 1AC, binary search..
阅读全文
LeetCode - Plus One
摘要:Plus One2013.12.22 03:37Given a number represented as an array of digits, plus one to the number.Solution: This problem seems quite easy, right? See if you can AC with one shot. Here're some good test cases for you: 0 + 1 = 1 1 + 1 = 2 34 + 1 = 35 99 + 1 = 100 Note that we write the n...
阅读全文
LeetCode - Add Binary
摘要:Add Binary2013.12.22 03:31Given two binary strings, return their sum (also a binary string).For example,a ="11"b ="1"Return"100".Solution: This is a problem about big integer addition, only in that it's binary. My solution is to add them up bit by bit, reverse the c
阅读全文
LeetCode - Merge Two Sorted Lists
摘要:Merge Two Sorted Lists2013.12.22 03:24Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.Solution: This is a FAQ in IT interview. Make sure you don't new any node, and watch out for any special cases like N
阅读全文
LeetCode - Minimum Path Sum
摘要:Minimum Path Sum2013.12.21 23:32Given amxngrid filled with non-negative numbers, find a path from top left to bottom right whichminimizesthe sum of all numbers along its path.Note:You can only move either down or right at any point in time.Solution1: Given a 2-d matrix of size m x n, with all eleme.
阅读全文
LeetCode - Unique Paths II
摘要:Unique Paths II2013.12.21 03:19Follow up for "Unique Paths":Now consider if some obstacles are added to the grids. How many unique paths would there be?An obstacle and empty space is marked as1and0respectively in the grid.For example,There is one obstacle in the middle of a 3x3 grid as ill
阅读全文
LeetCode - Unique Paths
摘要:Unique Paths2013.12.21 02:43A robot is located at the top-left corner of amxngrid (marked 'Start' in the diagram below).The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram
阅读全文
LeetCode - Rotate List
摘要:Rotate List2013.12.21 02:02Given a list, rotate the list to the right bykplaces, wherekis non-negative.For example:Given1->2->3->4->5->NULLandk=2,return4->5->1->2->3->NULL.Solution1: My first solution is clumsy with O(n^2) time complexity (X_X), at least it proves that
阅读全文
LeetCode - Spiral Matrix II
摘要:Spiral Matrix II2013.12.21 01:54Given an integern, generate a square matrix filled with elements from 1 ton2in spiral order.For example,Givenn=3,You should return the following matrix:[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]Solution: Still spiral order traversal of an m X n matrix, please see "
阅读全文
LeetCode - Length of Last Word
摘要:Length of Last Word2013.12.21 01:48Given a stringsconsists of upper/lower-case alphabets and empty space characters' ', return the length of last word in the string.If the last word does not exist, return 0.Note:A word is defined as a character sequence consists of non-space characters only.
阅读全文
LeetCode - Spiral Matrix
摘要:Spiral Matrix2013.12.21 01:37Given a matrix ofmxnelements (mrows,ncolumns), return all elements of the matrix in spiral order.For example,Given the following matrix:[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]You should return[1,2,3,6,9,8,7,4,5].Solution: Given an m X n matrix, traverse it in a clockwi.
阅读全文
LeetCode - Maximum Subarray
摘要:Maximum Subarray2013.12.17 14:21Find the contiguous subarray within an array (containing at least one number) which has the largest sum.For example, given the array[−2,1,−3,4,−1,2,1,−5,4],the contiguous subarray[4,−1,2,1]has the largest sum =6.click to show more practice.More practice:If you have fi
阅读全文
LeetCode - Pow(x, n)
摘要:Pow(x, n)2013.12.17 13:56Implement pow(x,n).Solution: Problem description is simple, so is the solution: divide and conquer. To calculae x^n, you'll need to know x^(n / 2) first. Later, let's deal with boundary values: 1. n = 0 2. n > 0 3. n 0 Think of any possible combinations and use ..
阅读全文
LeetCode - Anagrams
摘要:Anagrams2013.12.15 22:00Given an array of strings, return all groups of strings that are anagrams.Note: All inputs will be in lower-case.Solution: Anagrams means that strings composed of the same group of letters, such as [ate, eat, tea]. They'll become the same when sorted: aet. My solution is
阅读全文
LeetCode - Rotate Image
摘要:Rotate Image2013.12.15 21:40You are given annxn2D matrix representing an image.Rotate the image by 90 degrees (clockwise).Follow up:Could you do this in-place?Solution: Rotate an nXn 2D matrix in-place. See the picture below and that's how I did the rotation: ABCDA DEFEB CFXFC BEFED ...
阅读全文
LeetCode - Permutations II
摘要:Permutations II2013.12.15 05:30Given a collection of numbers that might contain duplicates, return all possible unique permutations.For example,[1,1,2]have the following unique permutations:[1,1,2],[1,2,1], and[2,1,1].Solution: This time the array may contain duplicates, so I implemented the next_p.
阅读全文
LeetCode - Permutations
摘要:Permutations2013.12.15 05:08Given a collection of numbers, return all possible permutations.For example,[1,2,3]have the following permutations:[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2], and[3,2,1].Solution: The STL library provides a function next_permutation(), which generates the next greater perm..
阅读全文
LeetCode - Multiply Strings
摘要:Multiply Strings2013.12.15 04:07Given two numbers represented as strings, return multiplication of the numbers as a string.Note: The numbers can be arbitrarily large and are non-negative.Solution: I just did a digit-by-digit multiplication. There seemed to be a very complicated O(n * log(n)) soluti.
阅读全文
LeetCode - Combination Sum II
摘要:Combination Sum II2013.12.15 03:51Given a collection of candidate numbers (C) and a target number (T), find all unique combinations inCwhere the candidate numbers sums toT.Each number inCmay only be usedoncein the combination.Note:All numbers (including target) will be positive integers.Elements in
阅读全文
LeetCode - Combination Sum
摘要:Combination Sum2013.12.15 03:10Given a set of candidate numbers (C) and a target number (T), find all unique combinations inCwhere the candidate numbers sums toT.Thesamerepeated number may be chosen fromCunlimited number of times.Note:All numbers (including target) will be positive integers.Elements
阅读全文
LeetCode - Count and Say
摘要:Count and Say2013.12.15 03:00The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...1is read off as"one 1"or11.11is read off as"two 1s"or21.21is read off as"one 2, thenone 1"or1211.Given an integern, generate thenthsequen
阅读全文
LeetCode - Valid Sudoku
摘要:Valid Sudoku2013.12.15 02:59Determine if a Sudoku is valid, according to:Sudoku Puzzles - The Rules.The Sudoku board could be partially filled, where empty cells are filled with the character'.'.A partially filled sudoku which is valid.Solution: For introduction of Sudoku game, please see Su
阅读全文
LeetCode - Search Insert Position
摘要:Search Insert Position2013.12.15 00:03Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.You may assume no duplicates in the array.Here are few examples.[1,3,5,6], 5 → 2[1,3,5,6], 2 → 1[1,3,5,6], 7
阅读全文
LeetCode - Search in Rotated Sorted Array
摘要:LeetCode - Search in Rotated Sorted Array2013.12.14 18:29Suppose a sorted array is rotated at some pivot unknown to you beforehand.(i.e.,0 1 2 4 5 6 7might become4 5 6 7 0 1 2).You are given a target value to search. If found in the array return its index, otherwise return -1.You may assume no dupli
阅读全文
LeetCode - Next Permutation
摘要:Next Permutation2013.12.7 05:14Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).The replacement must be in-place,
阅读全文
LeetCode - Divide Two Integers
摘要:Divide Two Integers2013.12.7 04:52Divide two integers without using multiplication, division and mod operator.Solution: Another bit-manipulation problem, integer division. Normally if we calculate x / y (x, y > 0), we'll subtract y from x until y 0 ? dividend : -(long long int)dividend;23 ...
阅读全文
LeetCode - Remove Element
摘要:Remove Element2013.12.7 04:33Given an array and a value, remove all instances of that value in place and return the new length.The order of elements can be changed. It doesn't matter what you leave beyond the new length.Solution1: My first solution is scan the array from both ends, if a target v
阅读全文
LeetCode - Remove Duplicates from Sorted Array
摘要:Remove Duplicates from Sorted Array2013.12.7 03:29Given a sorted array, remove the duplicates in place such that each element appear onlyonceand return the new length.Do not allocate extra space for another array, you must do this in place with constant memory.For example,Given input array A =[1,1,2
阅读全文
LeetCode - Swap Nodes in Pairs
摘要:Swap Nodes in Pairs2013.12.7 01:54Given a linked list, swap every two adjacent nodes and return its head.For example,Given1->2->3->4, you should return the list as2->1->4->3.Your algorithm should use only constant space. You maynotmodify the values in the list, only nodes itself ca
阅读全文
LeetCode - Merge k Sorted Lists
摘要:Merge k Sorted Lists2013.12.7 01:32Mergeksorted linked lists and return it as one sorted list. Analyze and describe its complexity.Solution: You must've done the job of merging two sorted linked lists quite often, this time it's k lists. The simple way is to find the smallest of all k head n
阅读全文
LeetCode - Generate Parentheses
摘要:Generate Parentheses2013.12.7 00:49Givennpairs of parentheses, write a function to generate all combinations of well-formed parentheses.For example, givenn= 3, a solution set is:"((()))", "(()())", "(())()", "()(())", "()()()"Solution: If you're
阅读全文
LeetCode - Valid Parentheses
摘要:Valid Parentheses2013.12.7 00:03Given a string containing just the characters'(',')','{','}','['and']', determine if the input string is valid.The brackets must close in the correct order,"()"and"()[]{}"are all valid but"(]&quo
阅读全文
LeetCode - Remove Nth Node From End of List
摘要:Remove Nth Node From End of ListGiven a linked list, remove thenthnode from the end of list and return its head.For example,Given linked list: 1->2->3->4->5, and n = 2.After removing the second node from the end, the linked list becomes 1->2->3->5.Note:Givennwill always be valid
阅读全文
LeetCode - Letter Combinations of a Phone Number
摘要:Letter Combinations of a Phone Number2013.12.6 19:52Given a digit string, return all possible letter combinations that the number could represent.A mapping of digit to letters (just like on the telephone buttons) is given below.Input:Digit string "23"Output: ["ad", "ae"
阅读全文
LeetCode - 3Sum
摘要:LeetCode - 3Sum2013.12.1 23:52Given an arraySofnintegers, are there elementsa,b,cinSsuch thata+b+c= 0? Find all unique triplets in the array which gives the sum of zero.Note:Elements in a triplet (a,b,c) must be in non-descending order. (ie,a≤b≤c)The solution set must not contain duplicate triplets.
阅读全文
LeetCode - Longest Common Prefix
摘要:LeetCode - Longest Common Prefix2013.12.1 23:23Write a function to find the longest common prefix string amongst an array of strings.Solution: For two string s1 and s2, compare the elements from the beginning, when the end or the first mismatch is found, the common prefix is found. For n strings s..
阅读全文
LeetCode - Roman to Integer
摘要:LeetCode - Roman to Integer2013.12.1 23:16Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from 1 to 3999.Solution: Given a Roman number, convert it to normal arabian form. Just do the conversion from left to right, one digit by one. Here is the wiki if yo..
阅读全文
LeetCode - Integer to Roman
摘要:LeetCode - Integer to Roman2013.12.1 22:56Given an integer, convert it to a roman numeral.Input is guaranteed to be within the range from 1 to 3999.Solution: First of all, for those who lacks background knowledge of Roman numerals(including me), here is the wiki: http://en.wikipedia.org/wiki/Rom...
阅读全文
LeetCode - Palindrome Number
摘要:LeetCode - Palindrome Number2013.12.1 22:24Determine whether an integer is a palindrome. Do this without extra space.click to show spoilers.Some hints:Could negative integers be palindromes? (ie, -1)If you are thinking of converting the integer to string, note the restriction of using extra space.Yo
阅读全文
LeetCode - Reverse Integer
摘要:LeetCode - Reverse Integer2013.12.1 22:12Reverse digits of an integer.Example1:x = 123, return 321Example2:x = -123, return -321click to show spoilers.Have you thought about this?Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!If the i
阅读全文
LeetCode - ZigZag Conversion
摘要:LeetCode - ZigZag Conversion2013.12.1 21:48The string"PAYPALISHIRING"is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)P A H NA P L S I I GY I RAnd then read line by line:"PAHNAPLSIIGYIR"
阅读全文
LeetCode - Add Two Numbers
摘要:LeetCode - Add Two Numbers2013.12.1 21:03You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.Input:(2 -> 4 -> 3) + (5 -> 6 -> 4)Outp
阅读全文
LeetCode - Longest Substring Without Repeating Characters
摘要:LeetCode - Longest Substring Without Repeating Characters2013.12.1 19:50Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bb
阅读全文
LeetCode - Median of Two Sorted Arrays
摘要:Median of Two Sorted Arrays2013.12.1 19:29There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).Solution: Given two sorted array, find out the median of all elements. My solution is straight.
阅读全文
LeetCode - Two Sum
摘要:LeetCode - Two Sum2013.12.1 02:30Given an array of integers, find two numbers such that they add up to a specific target number.The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answ
阅读全文
剑指Offer - 九度1523 - 从上往下打印二叉树
摘要:剑指Offer - 九度1523 - 从上往下打印二叉树2013-12-01 00:35题目描述:从上往下打印出二叉树的每个节点,同层节点从左至右打印。输入:输入可能包含多个测试样例,输入以EOF结束。对于每个测试案例,输入的第一行一个整数n(1 4 #include 5 using namespace std; 6 7 int main() 8 { 9 const int MAXN = 1005;10 queue qq;11 int i;12 int n;13 int x, y;14 int r;15 int a[MAXN][3];...
阅读全文
剑指Offer - 九度1522 - 包含min函数的栈
摘要:剑指Offer - 九度1522 - 包含min函数的栈2013-12-01 23:44题目描述:定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。输入:输入可能包含多个测试样例,输入以EOF结束。对于每个测试案例,输入的第一行为一个整数n(1 4 #include 5 using namespace std; 6 7 int main() 8 { 9 int n;10 int i;11 int tmp;12 vector st, min_st;13 char s[10];14 15 while(scanf("%d...
阅读全文