09 2013 档案
摘要: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).---
阅读全文
摘要: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.---public class Solution { public int maxProfit(int[] pr...
阅读全文
摘要: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...
阅读全文
摘要: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?---public class Solution { public ArrayList getRow(int rowIndex) { ArrayList rst = new ArrayList(); for (int ...
阅读全文
摘要: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]]---public class Solution { public ArrayList> generate(int numRows) { ArrayList> rst = new ArrayList>(); int i=0, ...
阅读全文
摘要: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...
阅读全文
摘要:You are given a string,S, and a list of words,L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.For example, given:S:"barfoothefoobarman"L:["foo", "
阅读全文
摘要:Implement 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, do not allocate extra memory.He
阅读全文
摘要:Given a stringSand a stringT, count the number of distinct subsequences ofTinS.A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie,"ACE"
阅读全文
摘要: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 \ 6click to show hints.---/** * D...
阅读全文
摘要: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.---/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) ...
阅读全文
摘要: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.---/** * Definition for binary tree * public class TreeNode { * int val; * TreeNo...
阅读全文
摘要:Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.---需要总长度,遍历一遍,1. 可以再这个时候吧list转成array, 费地方2. 或者跟array一样每次走半个长度找到mid, O(NlogN), logN层,每层遍历N,费时间/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode n...
阅读全文
摘要:Given an array where elements are sorted in ascending order, convert it to a height balanced BST.---/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public TreeNode...
阅读全文
摘要:Given a binary tree, return thebottom-up level ordertraversal 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 7return its bottom-up level order traversal as:[ [15,7] [9,20], [3],]conf...
阅读全文
摘要: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
阅读全文
摘要: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......and its solution numbers marked in red.--- public boolean solveSudoku(char[][] board) { ...
阅读全文
摘要: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.---public class Solution { public boolean isValidSudoku(char[][] board) { int n = ..
阅读全文
摘要: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
阅读全文
摘要:Follow up for N-Queens problem.Now, instead outputting board configurations, return the total number of distinct solutions.---跟50 -Queue思路一样问题是那个不能用int total带入,而是int[] 即便是一位数组,如果只是int作为参数,只是copy the value to the function, total本身没有变,如果是int[], 相当吧variable's reference带入, 可以改变参数本身的值,试过 Integer,也不行,
阅读全文
摘要: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'.'b
阅读全文
摘要:Given preorder and inorder traversal of a tree, construct the binary tree.Note:You may assume that duplicates do not exist in the tree.---/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */publ...
阅读全文
摘要: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.---/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) ...
阅读全文
摘要: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, 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]]confused what"{1,#,2,3}"means?> read more .
阅读全文
摘要: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.---/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right...
阅读全文
摘要: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?confused what"{1,#,2,3}"means?> read more on how binary tree is seria
阅读全文
摘要: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
阅读全文
摘要:Givens1,s2,s3, find whethers3is formed by the interleaving ofs1ands2.For example,Given:s1="aabcc",s2="dbbca",Whens3="aadbbcbcac", return true.Whens3="aadbbbaccc", return false.---DP---Solution1 : 2维数组public class Solution { public boolean isInterleave(String s
阅读全文
摘要:Givenn, generate all structurally uniqueBST's(binary search trees) that store values 1...n.For example,Givenn= 3, your program should return all 5 unique BST's shown below. 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ ...
阅读全文
摘要: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 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 on how binary tree is serialized on OJ.---ino
阅读全文
摘要: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?n? length of list.---/** * Definition for singly-linked list. * public c
阅读全文
摘要: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], []]---public class...
阅读全文
摘要: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.---public class Solution { public void merge(int A[], int m, int B[], int ...
阅读全文
摘要: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.---1. O(n^3)2. 很想84, largest rectangle in histogra,每一行存以当前行为底的柱状图, 求最大矩形面积。O(N^2)---10/01 YC versionpublic class Solution { public int maximalRectangle(char[][] matrix) { ...
阅读全文
摘要: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
阅读全文
摘要: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.---10/01 YC version:/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next
阅读全文
摘要: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.---public class Solution { public boolean search(int[] A, int target) { return helper(A...
阅读全文
摘要: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.---constant space, --> swap!桶排序,只不过不许用额外空间。每次当A[i]!= i的时候,将A[i]与A[A[i]]交换,也就是把A[i]放到它应该在的位置A[A[i]]直到无法交换位置。--
阅读全文
摘要: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
阅读全文
摘要: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].---public class Solution { public int removeDuplicates(int[] A) { if(A.length <= 2) return ...
阅读全文
摘要: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
阅读全文
摘要: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], []]---Compare to leet 77, combin...
阅读全文
摘要: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],]---YC 10/20 versionpublic class Solution { public ArrayList> combine(int n, int k) { ArrayList> rst = new Ar...
阅读全文
摘要: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"BANC".Note:If there is no such window in S that covers all characters in T, return the emtpy
阅读全文
摘要: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 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 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---public class Solution { public int minDi...
阅读全文
摘要:Given 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.---stack---public class Solution { public String simplifyPath(String path) { if (path == null || path
阅读全文
摘要: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?---map[n+1]!!!(0-n), length = n+1public class Solution { public int climbStairs(int n) { int[] map = new int[n+1]; ...
阅读全文
摘要:Implementint sqrt(int x).Compute and return the square root ofx.---BST---public static int helper(int x, int l, int r) { if (l x || l > r) return Math.min(l, r); // x=2, rst=1, x=8, rst=2; int mid = l + (r - l) / 2; if (x / mid == mid) return mid; else if (x /...
阅读全文
摘要:Given a number represented as an array of digits, plus one to the number.---return Arrays.copyOfRange(rst, 1, n+1);---public class Solution { public int[] plusOne(int[] digits) { int n = digits.length; int[] rst = new int[n+1]; int carry = 1; for(int i=...
阅读全文
摘要: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
阅读全文
摘要: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.---/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val =
阅读全文
摘要: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,
阅读全文
摘要:A 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 below).How many possible uni
阅读全文
摘要: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.---DP !!!---1. basic 二维数组注意i=0, j=0,其他min[i][j] = Math.min(min[i][j-1], min[i-1][j]) + grid[
阅读全文
摘要: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.---/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * ...
阅读全文
摘要:Given two binary strings, return their sum (also a binary string).For example,a ="11"b ="1"Return"100".---public class Solution { public String addBinary(String a, String b) { // convert to int if(a == null || b == null) return null; int x = 0; for(int i=...
阅读全文
摘要:Implement pow(x,n).---Recursivedivide-and-conquer approachO(lgn)---public class Solution { double pow(double x, int n) { if (n == 0) return 1.0; // Compute x^{n/2} and store the result into a temporary // variable to avoid unnecessary computing double half = pow(x,...
阅读全文
摘要:Given an array of strings, return all groups of strings that are anagrams.Note: All inputs will be in lower-case.---public class Solution { public ArrayList anagrams(String[] strs) { ArrayList rst = new ArrayList(); HashMap> map = new HashMap>(); for (String s : strs)...
阅读全文
摘要:You are given annxn2D matrix representing an image.Rotate the image by 90 degrees (clockwise).Follow up:Could you do this in-place?---public class Solution { public void rotate(int[][] matrix) { if(matrix == null) return; if(matrix.length != matrix[0].length) return; ...
阅读全文
摘要: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].---sort arraycheck duplicationrecursive---public class Solution { public ArrayList> permuteUnique(int[] num)..
阅读全文
摘要: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 two numbers represented as strings, return multiplication of the numbers as a string.Note: The numbers can be arbitrarily large and are non-negative.---09/21, Review顺序,最高位是0要去掉public class Solution { public String multiply(String num1, String num2) { if (num1.equals("0") || num...
阅读全文
摘要: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.Your goal is to reach the last index in the minimum number of jumps.For example:Given array A =[2,3,1,1,4]The minimum n
阅读全文
摘要: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].---参考cc150 9.5O(N!) N factorial---1. Interationpublic class Solution { public ArrayList> permute(int[] num) { Array...
阅读全文
摘要: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
阅读全文
摘要: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---BST---public cl
阅读全文
摘要: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].---public
阅读全文
摘要: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.---Basic idea is Binary search-i
阅读全文
摘要:Divide two integers without using multiplication, division and mod operator.---public class Solution { public int divide(int dividend, int divisor) { boolean sign1 = dividend >=0; boolean sign2 = divisor >=0; long a = Math.abs((long)dividend); long b = ...
阅读全文
摘要:mplement strStr().Returns a pointer to the first occurrence of needle in haystack, ornullif needle is not part of haystack.---public class Solution { public String strStr(String haystack, String needle) { if(haystack == null || needle == null) return null; int...
阅读全文
摘要:Given 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.---Similar to 25, remove dup from a sorted array---public class Solution { public int removeElement(int[]
阅读全文
摘要: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
阅读全文
摘要:Given a linked list, reverse the nodes of a linked listkat a time and return its modified list.If the number of nodes is not a multiple ofkthen left-out nodes in the end should remain as it is.You may not alter the values in the nodes, only nodes itself may be changed.Only constant memory is allowed
阅读全文
摘要:Given 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 can be changed.---Solution1: Interat
阅读全文
浙公网安备 33010602011771号