08 2013 档案
摘要:Write 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 the following matrix:[ [1, 3, ...
阅读全文
摘要:Given a 2D board and a word, find if the word exists in the grid.The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.For example,Givenboard=[ [&q
阅读全文
摘要:Follow 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].[解题思路]双指针问题,还是使用count来保存结果数组的大小与Remove Duplicates from Sorted Array唯一区别在添加start, end标识duplicates区间如果当
阅读全文
摘要:Given 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],Your function should return length =2, and A is
阅读全文
摘要:Persistent environment variablesSo far we've only discussed ways set an environment variable value temporarily until the shell session in which it was set is closed. One may wonder if there is a way to somehow permanently set an environment variable to a certain value.Note:The shell config files
阅读全文
摘要:Implement wildcard pattern matching with support for'?'and'*'.'?' Matches any single character.'*' Matches any sequence of characters (including the empty sequence).The matching should cover the entire input string (not partial).The function prototype should be:bool i
阅读全文
摘要:Given a strings1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.Below is one possible representation ofs1="great": great / \ gr eat / \ / \g r e at / \ a tTo scramble the string, we may choose any non-leaf no...
阅读全文
摘要:Given a binary tree, return thezigzag level ordertraversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).For example:Given binary tree{3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7return its zigzag level order traversal as:[ [3], ...
阅读全文
摘要:Given a binary tree, flatten it to a linked list in-place.For example,Given 1 / \ 2 5 / \ \ 3 4 6The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6[解题思路] 1 \ ...
阅读全文
摘要:Given an indexk, return thekthrow of the Pascal's triangle.For example, givenk= 3,Return[1,3,3,1].Note:Could you optimize your algorithm to use onlyO(k) extra space?[解题思路]从后往前计算,另外Trangle的index从0开始,故分配的数组大小为rowIndex + 1 1 public class Solution { 2 public ArrayList getRow(int rowIndex) { 3 ...
阅读全文
摘要:GivennumRows, generate the firstnumRowsof Pascal's triangle.For example, givennumRows= 5,Return[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1]][解题思路]第三行开始,每行除边界元素外,每个元素ai都是由ai-1 + ai构成 1 public class Solution { 2 public ArrayList> generate(int numRows) { 3 // Start typing your Ja...
阅读全文
摘要:Given inorder and postorder traversal of a tree, construct the binary tree.Note:You may assume that duplicates do not exist in the tree.[解题思路]与上题类似Construct Binary Tree from Preorder and Inorder Traversal确定左右子树的序列,递归建立树,唯一不同在于后序遍历,根节点在最后一个元素 1 /** 2 * Definition for binary tree 3 * public class Tr..
阅读全文
摘要:Given preorder and inorder traversal of a tree, construct the binary tree.Note:You may assume that duplicates do not exist in the tree.[解题思路]由前序遍历知第一个节点是根节点,根据此节点值去中序遍历集合中找该root值所处位置,该位置之前的数属于左子树,之后的属于右子树,即找到左子树和右子树所处的子序列,接下来就可以用递归来完成递归的终止条件:preorder中仅有一个元素且preorder中的元素和inorder中元素相同 1 /** 2 * @auth.
阅读全文
摘要:Givenn, 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 / / \ \ 2 1 ...
阅读全文
摘要:Given two wordsword1andword2, find the minimum number of steps required to convertword1toword2. (each operation is counted as 1 step.)You have the following 3 operations permitted on a word:a) Insert a characterb) Delete a characterc) Replace a character[解题思路]这里用ed(s1, s2)来表示s1, s2之间的edit distanceba
阅读全文
摘要:Given 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.[解题思路]与Unique Paths类似,只是把求路径数改成求最小路径和目标函数:sum[i][j] = grid[i][j] + Math.min(sum[i+1][j], sum
阅读全文
摘要:Follow 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 illustrated below.[ [0,0,0], [0,1,
阅读全文
摘要:1.DP bottom up 1 public int uniquePaths(int m, int n) { 2 // Start typing your Java solution below 3 // DO NOT write main() function 4 int[][] steps = new int[m+2][n+2]; 5 for(int i = 0; i = 1; i--){13 for(int j = n; j >= 1; j--){14 steps[i...
阅读全文
摘要:Given amxnmatrix, if an element is 0, set its entire row and column to 0. Do it in place.Follow up:Did you use extra space?A straight forward solution using O(mn) space is probably a bad idea.A simple improvement uses O(m+n) space, but still not the best solution.Could you devise a constant space so
阅读全文
摘要:Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.For example, given the following triangle[ [2], [3,4], [6,5,7], [4,1,8,3]]The minimum path sum from top to bottom is11(i.e.,2+3+5+1= 11).Note:Bonus point if you are a...
阅读全文
摘要:Here is adifficulty and frequency distribution chartfor each problem (which I got from the Internet and is very useful).Dynamic ProgrammingEdit DistanceMaximum SubarrayMinimum Path SumUnique PathsUnique Paths IILongest Palindromic SubstringInterleaving StringTriangleDistinct SubsequencesDecode WaysP
阅读全文
摘要:Implementint sqrt(int x).Compute and return the square root ofx.[解题思路]使用二分法来求解开方,在一个区间中,每次拿中间数的平方来试验,如果小了,再拿右区间的中间数来试。比如求解sqrt(16), (0+16) / 2 = 8, 8*8 = 64 > 16, 选择左区间(0+7)/2 = 3, 3*3 = 9 16继续选择左区间(4+4)/2 = 4, 4*4=16这里为了防止x输入过大时,mid*mid会溢出,把mid*mid与x的比较换成mid与x/mid之间的比较 1 public int sqrt(int x) {
阅读全文
摘要:You 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?large data TLE递归解法的时间复杂度为:O(2^lgn), 故当n逐渐变大时,由于计算重复解,时间复杂度呈指数级增长 1 public int climbStairs(int n) { 2 // Start typing your Java sol...
阅读全文
摘要:Follow up for problem "Populating Next Right Pointers in Each Node".What if the given tree could be any binary tree? Would your previous solution still work?Note:You may only use constant extra space.For example,Given the following binary tree, 1 / \ 2 3 / \ \ 4 5 ...
阅读全文
摘要:Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; }Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set toNULL.Initially, all next pointers are set toNULL.N...
阅读全文
摘要:Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.Top down 的解题方法:1. 将LinkedList的值保存到一个数组中,转化成Convert Sorted Array to Binary Search Tree 来解决时间复杂度为O(n), 空间复杂度为O(n) 1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 *...
阅读全文
摘要:Given an array where elements are sorted in ascending order, convert it to a height balanced BST.[解题思路]递归确定每棵树的根节点的值,这里根节点的值是二分搜索的中值由于这里是有序数组,确定root的时间复杂度为O(1), 整个算法的时间复杂度为O(n),n为节点数目。 1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * ...
阅读全文
摘要:Given 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 a combination (a1,a2, � ,ak) must
阅读全文
摘要:Given 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 in a combination (a1,a2, � ,ak
阅读全文
摘要:Given 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],] 1 public class Solution { 2 public ArrayList> combine(int n, int k) { 3 // Start typing your Java solution below...
阅读全文
摘要:Given an unsorted array of integers, find the length of the longest consecutive elements sequence.For example,Given[100, 4, 200, 1, 3, 2],The longest consecutive elements sequence is[1, 2, 3, 4]. Return its length:4.Your algorithm should run in O(n) complexity.[解题思路]数组,O(n)---->使用hash,空间换时间对于当前数N
阅读全文
摘要:Say you have an array for which theithelement is the price of a given stock on dayi.Design an algorithm to find the maximum profit. You may complete at mosttwotransactions.Note:You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 1 public c
阅读全文
摘要:Say you have an array for which theithelement is the price of a given stock on dayi.Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at
阅读全文
摘要:Say you have an array for which theithelement is the price of a given stock on dayi.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.[解题思路]记录一个最小值,每次拿当前值与最小值比较,如果两者差>profit,则更新profit 1 publ
阅读全文
摘要:Given a binary tree, determine if it is height-balanced.For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees ofeverynode never differ by more than 1.[解题思路]检查每个node是否是balanced,大数据集挂掉了 1 /** 2 * Definition for binary tree 3 * public class..
阅读全文
摘要:Reverse 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 + 1 && count <= n){36 p.next = pre;37 }38 pre = p;39 ...
阅读全文
摘要:1.解决win7 64位[ODBC 驱动程序管理器] 未发现数据源名称并且未指定默认驱动程序http://wwwu8.wap.blog.163.com/w2/blogDetail.do?hostID=www.u8&blogId=fks_087066084095089071083087095067072081082070081084083075093http://blog.163.com/misfans_001/blog/static/485107392012930105140602/2.本地IIS7.5调试出现500错误解决方法http://lml0414.love.blog.163.
阅读全文
摘要:Two 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?1.O(n) space solution中序遍历该BST,得到所有整数对齐排好序,对节点重新进行赋值 1 /** 2 * Definition for bina.
阅读全文
摘要:Given 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 thanthe node's key.Both the left and ri
阅读全文
摘要:Given 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.[解题思路]在头结点之前添加safeguard,防止处理一开始就是连续节点的情况当发现连续节点时,line
阅读全文
摘要:Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * ...
阅读全文
摘要:Given a binary tree, find its maximum depth.The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.Recursive Version 1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNo...
阅读全文
摘要:Given a binary tree, return thelevel ordertraversal of its nodes' values. (ie, from left to right, level by level).For example:Given binary tree{3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7return its level order traversal as:[ [3], [9,20], [15,7]][解题思路]1.可以维护两个queue,当前层一个,下一层一个2.记录下一层元素个数...
阅读全文
摘要:Given 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?Recursive Version 1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * ...
阅读全文
摘要:Given 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], [1,2], []][解题思路]本题与Subset...
阅读全文
摘要:Given 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. 1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * Lis
阅读全文
摘要:Given 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 are not suppose to use the l
阅读全文
摘要:Given 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], []] 1 public class Solution { 2 ...
阅读全文
摘要:Given an array of words and a lengthL, format the text such that each line has exactlyLcharacters and is fully (left and right) justified.You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces' 'when necessary so that each line
阅读全文
摘要:Given a number represented as an array of digits, plus one to the number. 1 public class Solution { 2 public int[] plusOne(int[] digits) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 int len = digits.length; 6 digits[len - 1] += ...
阅读全文
摘要:Given two binary strings, return their sum (also a binary string).For example,a ="11"b ="1"Return"100".[解题思路]将a,b转成10进制相加得到结果再转成二进制,可以过small,跑large时溢出"10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101", "11010
阅读全文
摘要:Merge 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. 1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * v...
阅读全文
摘要:Given 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.[解题思路]初始的想法是类似于求倒数第k个数,结果发现k可能会比len大,到网上搜索了下:从head节点开始跑,一直跑到尾节点,得到len,将尾节点的next指针指向head,接着跑(len -n) % len步,断开这里需注意(len -n) %
阅读全文
摘要:Given a collection of intervals, merge all overlapping intervals.For example,Given[1,3],[2,6],[8,10],[15,18],return[1,6],[8,10],[15,18].[解题思路]这里使用Insert interval的解题过程,将待合并的interval依次插入 1 /** 2 * Definition for an interval. 3 * public class Interval { 4 * int start; 5 * int end; 6 * ...
阅读全文
摘要:Given a set ofnon-overlappingintervals, insert a new interval into the intervals (merge if necessary).You may assume that the intervals were initially sorted according to their start times.Example 1:Given intervals[1,3],[6,9], insert and merge[2,5]in as[1,5],[6,9].Example 2:Given[1,2],[3,5],[6,7],[8
阅读全文
摘要:Given an unsorted array of integers, find the length of the longest consecutive elements sequence.For example,Given[100, 4, 200, 1, 3, 2],The longest consecutive elements sequence is[1, 2, 3, 4]. Return its length:4.Your algorithm should run in O(n) complexity.large data TLE 1 public class Solution
阅读全文
摘要:Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.An example is the root-to-leaf path1->2->3which represents the number123.Find the total sum of all root-to-leaf numbers.For example, 1 / \ 2 3The root-to-leaf path1->2represents the number12.T
阅读全文
摘要:The 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,2]. Its gray code s
阅读全文
摘要:Given 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,return1->2->2->4->3-
阅读全文
摘要:Find 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.More practice:If you have figured out the O(n) solution, try coding another solution usi
阅读全文
摘要:Then-queens puzzle is the problem of placingnqueens on ann�nchessboard such that no two queens attack each other. Given an integern, return all distinct solutions to then-queens puzzle.Each solution contains a distinct board configuration of then-queens' placement, where'Q'and'....
阅读全文
摘要:The set[1,2,3,…,n]contains a total ofn! unique permutations.By listing and labeling all of the permutations in order,We get the following sequence (ie, forn= 3):"123""132""213""231""312""321"Givennandk, return thekthpermutation sequence.Not
阅读全文
摘要:TODOhttp://www.iteye.com/topic/1119854http://my.oschina.net/lbstarsky/blog/67774http://blog.csdn.net/lovesqcc/article/details/6256415
阅读全文
摘要: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 3But the following is not: 1 / \ 2 2 \ \ 3 3Note:Bonus points if you could solve it both recursively and iterati...
阅读全文
摘要:Given 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. 1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * ...
阅读全文
摘要:Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.For example:Given the below binary tree andsum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ ...
阅读全文
摘要:Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.For example:Given the below binary tree andsum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1return[ [5,4,11,2]...
阅读全文
摘要:Given 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.For example,Givens="Hello Worl
阅读全文
摘要:Given a strings, partitionssuch that every substring of the partition is a palindrome.Return the minimum cuts needed for a palindrome partitioning ofs.For example, givens="aab",Return1since the palindrome partitioning["aa","b"]could be produced using 1 cut.[解题思路]记录所有合法的
阅读全文
摘要:Given a strings, partitionssuch that every substring of the partition is a palindrome.Return all possible palindrome partitioning ofs.For example, givens="aab",Return [ ["aa","b"], ["a","a","b"] ]列出字符串分解的题基本都是DFS,本题是找出s所有合数的分解,故i=start在perm
阅读全文
摘要:Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.For example,"A man, a plan, a canal: Panama"is a palindrome."race a car"isnota palindrome.Note:Have you consider that the string might be empty? This is a good question to
阅读全文
摘要:Given 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 ]]java 中是传值的,将count作为返回值返回 1 public static int[][] generateMatrix(int n) { 2 // Start typing your Java...
阅读全文
摘要:Given 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]. 1 public class Solution { 2 public ArrayList spiralOrder(int[][] matrix) { 3 ...
阅读全文
摘要:Implement pow(x,n).直接计算会超时TLE 1 public double pow(double x, int n) { 2 // Start typing your Java solution below 3 // DO NOT write main() function 4 if(n == 0) 5 return 1; 6 7 double result = 1; 8 if(n > 0){ 9 while(n > 0){10 ...
阅读全文
摘要:Given an array of strings, return all groups of strings that are anagrams.Note: All inputs will be in lower-case.Input: ["tea","and","ate","eat","den"]Output:["tea","ate","eat"]["",""]------------->
阅读全文
摘要:You are given annxn2D matrix representing an image.Rotate the image by 90 degrees (clockwise).Follow up:Could you do this in-place?如下图,首先沿逆对角线翻转一次,然后按x轴中线翻转一次。 1 public void rotate(int[][] matrix) { 2 // Start typing your Java solution below 3 // DO NOT write main() function 4 ...
阅读全文
摘要:Given 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].解题思路:Permutations 那题输入是不包含重复元素的,故生成的排列都是不同的,II中输入元素可能相同因而可能会产生相同的排列,这里需要去重,没有找到很好的剪枝条件,这里使用HashSet来去重,当发现已经添加过该组合
阅读全文
摘要:Given 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].求每个位置所有可能出现的情况:固定第一个字符,然后求后面所有字符的排列。这个时候仍把后面的所有字符分成两部分:后面字符的第一个字符,以及这个字符之后的所有字符 1 public class Solution { 2 public ArrayList> per.
阅读全文
摘要: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 if you are able to reach the last index.For example:A =[2,3,1,1,4], returntrue.A =[3,2,1,0,4], returnfalse.[解
阅读全文
摘要:Given two numbers represented as strings, return multiplication of the numbers as a string.Note: The numbers can be arbitrarily large and are non-negative.大整数乘法,一位一位往上乘,注意进位的处理即可。此外,注意0的处理 1 public class Solution { 2 public String multiply(String num1, String num2) { 3 // Start typing yo...
阅读全文
摘要: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 aremandnrespectively.从后往前遍历,减少移动次数。此题与替换字符串类似 1 public void merge(int A[], int m, int B[], int n)
阅读全文
摘要:Given 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,return1->2->2->4->3-
阅读全文
摘要:Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
阅读全文
摘要:Givennnon-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.Above is a histogram where width of each bar is 1, given height =[2,1,5,6,2,3].The largest rectangle is shown in the shaded area, which has ar
阅读全文
摘要:Givennnon-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.For example,Given[0,1,0,2,1,0,1,3,2,1,2,1], return6.The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of
阅读全文
摘要:Given an unsorted integer array, find the first missing positive integer.For example,Given[1,2,0]return3,and[3,4,-1,1]return2.Your algorithm should run inO(n) time and uses constant space.本题要求在O(n)时间内完成,并且使用O(1)空间O(n)时间则说明要使用hash来解本题,O(1)空间要求不能另开一个数组来进行hash,只能声明变量或者使用输入数组来进行这题是使用输入数组来进行hash本题的输入正整数范
阅读全文
摘要:Given 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 in a combination (a1,a2, � ,ak
阅读全文
摘要:The 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 thenthsequence.Note: The sequence of inte
阅读全文
摘要:Write a program to solve a Sudoku puzzle by filling the empty cells.Empty cells are indicated by the character'.'.You may assume that there will be only one unique solution.A sudoku puzzle...思路:回溯(Backtracking),回溯题练得太少,知道应该用回溯写,但不知如何下笔。。。。。下面代码是参考网上博客写的,回溯题有如下几点需要注意:1. 应当有个独立的isValid判断函数2. 递
阅读全文
摘要:Determine 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.判断数独是否合法:1. 同一行中1-9出现次数不重复2. 同一列中1-9出现次数不重复3. 9宫格中1-9出现次数不重复这里将1,2的判断在一个循环体中进行,分开进行跑
阅读全文
摘要:Given 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 → 4[1,3,5,6], 0 → 0思路:二分搜索,如search到则返
阅读全文
摘要:Given a sorted array of integers, find the starting and ending position of a given target value.Your algorithm's runtime complexity must be in the order ofO(logn).If the target is not found in the array, return[-1, -1].For example,Given[5, 7, 7, 8, 8, 10]and target value 8,return[3, 4].思路:使用二分搜索
阅读全文
摘要:Follow 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.上题中A[l] A[m]) {23 // upper is sorted24 if(A[m] < target && target <= A[r...
阅读全文
摘要:Suppose 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 duplicate exists in the array.使用二分搜索需计算l,r 左右边界1.当A[l] <= A
阅读全文
摘要:Given a string containing just the characters'('and')', find the length of the longest valid (well-formed) parentheses substring.For"(()", the longest valid parentheses substring is"()", which has length = 2.Another example is")()())", where the longest
阅读全文