01 2014 档案
摘要:Given two binary strings, return their sum (also a binary string).For example,a ="11"b ="1"Return"100".StringBuilder + reverse methodpublic class Solution { public String addBinary(String a, String b) { if(a == null || a.equals("")) return b; if(b == null || b
阅读全文
摘要:Given an array of strings, return all groups of strings that are anagrams.Note: All inputs will be in lower-case.思路:建Hashtable,用排序过的string作为key,它的anagram作为ArrayList题目的意思是给一个String数组,找出其中由相同字母组成的单词。例如:S = ["abc", "bca", "bac", "bbb", "bbca", "abc
阅读全文
摘要: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正确的解出来方法是用二维的dp。假如我们要将字符串str1变成str2,sstr1(i)是s
阅读全文
摘要:http://blog.csdn.net/twtsa/article/details/8120269http://blog.csdn.net/sunjilong/article/details/8254108public class Solution { public int maximalRectangle(char[][] matrix) { if(matrix.length=0;j--){ // 如果遍历元素为'1',right[j]取R和right[j]中的最小值 if(matrix[i][j]=='1')...
阅读全文
摘要: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) { v...
阅读全文
摘要:Swap Nodes in PairsGiven 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./*
阅读全文
摘要: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].Analysis:The idea of this classic problem is to use backtracking.We want to get permutations, which is mainly about swap values in th
阅读全文
摘要:Permutation SequenceThe 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 thekthperm
阅读全文
摘要:Implementint sqrt(int x).Compute and return the square root ofx.public class Solution { public int sqrt(int x) { int start = 0; int end = x; if(x == 0 || x == 1) return x; while(start x/m){ end = m -1; }else{ s...
阅读全文
摘要:Search in Rotated Sorted Array ||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
阅读全文
摘要: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; *...
阅读全文
摘要:[解题思路]创建一个新的interval集合,然后每次从旧的里面取一个interval出来,然后插入到新的集合中。没什么好说的,遍历已有vector,如果当前interval小于newinterval,插入当前;如果当前interval大于newInterval,则插入newInterval及当前;如果两者重叠,merge以后插入新的interval。实现中之所以重新new了一个vector来存放结果的原因,是不愿意破坏传入参数。在原有的vector上面直接修改的话,唯一的区别就是,一旦发现当前interval大于newInterval,就应该return了。/** * Definition
阅读全文
摘要:Implement regular expression matching with support for'.'and'*'.'.' Matches any single character.'*' Matches zero or more of the preceding element.The matching should cover the entire input string (not partial).The function prototype should be:bool isMatch(const char
阅读全文
摘要:public class Solution { public int romanToInt(String s) { int result = 0; if(s == null || s.length() == 0){ return result; } for(int i = 0; i 0 && cToI(s.charAt(i)) > cToI(s.charAt(i-1))){ // IV(4) result = 1 + 5 - 1*2 = 4 ...
阅读全文
摘要:Solution andPrecautions:Very similar to the classical merger sort for two sorted arrays, since the k linked list are already sorted, we just find the smallest number among the heads list[i][0] (i=0,…k-1), of course, if some list already reached to the end, that is list[i][0] is NULL, we just ignore
阅读全文
摘要: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'.&
阅读全文
摘要: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.[解题思路]分析题目给定3个字符串(s1,s2,s3),看s3是否是有s1和s2通过交织可以得到。可以这么来看这个问题,每次从s3开头拿出来一个字符,如果s1的开头或者
阅读全文
摘要:package validNumber;public class Solution { public boolean isNumber(String s) { if (s == null) return false; char[] sArr = s.trim().toCharArray(); if (sArr.length == 0) return false; // if string 长度为1 且不是数字 if (sArr.length == 1 && !Characte...
阅读全文
摘要:Given a number represented as an array of digits, plus one to the number.public class Solution { public int[] plusOne(int[] digits) { int carry = 0; int length = digits.length; digits[length-1] = digits[length -1] + 1; for(int i = length -1 ; i>=0; i--){ ...
阅读全文
摘要:Given two words (startandend), and a dictionary, find the length of shortest transformation sequence fromstarttoend, such that:Only one letter can be ...
阅读全文
摘要:public class Solution { public int divide(int dividend, int divisor) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(dividend == 0) return 0; if(divisor == 1) return...
阅读全文
摘要:Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.If such arrangement is not possibl...
阅读全文
摘要:public class Solution { public boolean isPalindrome(String s) { if(s == null || s.length() <2 ){ return true; } String mystring = s.replaceAll("[^A-Za-z0-9]", ""); mystring = mystring.toLowerCase(); // 只需遍历前一半就可以了 for(int i = 0...
阅读全文
摘要:[解题思路]典型的递归。一步步构造字符串。当左括号出现次数 generateParenthesis(int n) { ArrayList result = new ArrayList(); StringBuilder builder = new StringBuilder(); generate(result, builder, n, n); return result; } public void generate(ArrayList result, StringBuilder builder, int start,...
阅读全文
摘要:123 * 45 615 + 492 = 5535public class Solution { public String multiply(String num1, String num2) { int l1 = num1.l...
阅读全文
摘要:有三种情况要考虑:1. 如果两个substring相等的话,则为true2. 如果两个substring中间某一个点,左边的substrings为scramble string,同时右边的substrings也为scramble string,则为true3. 如果两个substring中间某一个点,s1左边的substring和s2右边的substring为scramblestring, 同时s1右边substring和s2左边的substring也为scramblestring,则为truepublic class Solution { public boolean isScramb...
阅读全文
摘要:参考:http://fisherlei.blogspot.com/2012/12/leetcode-median-of-two-sorted-arrays.html[解题思路]O(n)的解法比较直观,直接merge两个数组,然后求中间值。而对于O(log(m+n))显然是用二分搜索了, 相当于“Kth element in 2 sorted array”的变形。如果(m+n)为奇数,那么找到“(m+n)/2+1 th element in 2 sorted array”即可。如果(m+n)为偶数,需要找到(m+n)/2 th 及(m+n)/2+1 th,然后求平均。而对于“Kth elemen
阅读全文
摘要:Returns a pointer to the first occurrence of needle in haystack, ornullif needle is not part of haystack\遍历算法 1 public class Solution { 2 public String strStr(String haystack, String needle) { 3 4 if(haystack == null || needle == null) 5 return null; 6 if(needl...
阅读全文
摘要: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.public class Solution { public int removeElement(int[] A, int elem) { int len = A.length; in...
阅读全文
摘要:Two pointerspublic class Solution { public ArrayList> threeSum(int[] num) { ArrayList> result = new ArrayList>(); Arrays.sort(num); ...
阅读全文
摘要:public class Solution { public int[] twoSum(int[] numbers, int target) { // IMPORTANT: Please reset any member data you declared, as ...
阅读全文
摘要: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 / \ ...
阅读全文
摘要:/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if(l1 == null) return l2;...
阅读全文
摘要:递归解法/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public boolean isValidBST(TreeNode root) { return isValidBSTHelper(root, Integer.MIN_VALUE, Integer.MAX_...
阅读全文
摘要: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; * TreeNode ...
阅读全文
摘要: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 n) ...
阅读全文
摘要:参考:http://www.cnblogs.com/reynold-lei/p/3385290.html http://www.cnblogs.com/feiling/p/3302242.html罗马数字共有7个,即I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)。在较大的罗马数字的右边记上较小的罗马数字,表示大数字加小数字。在较大的罗马数字的左边记上较小的罗马数字,表示大数字减小数字。左减的数字有限制,仅限于I、X、C。比如45不可以写成VL,只能是XLV但是,左减时不可跨越一个位数。比如,99不可以用IC()表示,而是用XCIX()表示。(等同于阿拉.
阅读全文
摘要: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 cl
阅读全文
摘要:参考 http://fisherlei.blogspot.com/2012/12/leetcode-largest-rectangle-in-histogram.html以下摘自水中的鱼:这样的话,就可以通过大数据。但是这个优化只是比较有效的剪枝,算法仍然是O(n*n).想了半天,也想不出来O(n)的解法,于是上网google了一下。如下图所示,从左到右处理直方,i=4时,小于当前栈顶(及直方3),于是在统计完区间[2,3]的最大值以后,消除掉阴影部分,然后把红线部分作为一个大直方插入。因为,无论后面还是前面的直方,都不可能得到比目前栈顶元素更高的高度了。这就意味着,可以维护一个递增的栈,每次
阅读全文
摘要:Trapping Rain WaterGiven n non-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], return 6.The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In
阅读全文
摘要: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 / \ ...
阅读全文
摘要: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?public class Solution { public int climbStairs(int n) { int[] level = new int[n+1]; level[0] = 0; level[1] = 1; ...
阅读全文
摘要:You 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 ...
阅读全文
摘要:Search in Rotated Sorted ArraySuppose 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.A[
阅读全文
摘要:这里使用了额外的存储空间,可以使用双指针来实现,不需额外的存储空间./** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode deleteDuplicates(ListNode head) { ...
阅读全文
摘要:Given 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"(]"and"([)]"are not.pub
阅读全文
摘要:public class Solution { public void setZeroes(int[][] matrix) { if(matrix.length == 0) { return; } int r = matrix.length; int c = matrix[0].length; boolean rZeros = false; boolean cZeros = false; for(int i = 0 ; i < r ; i++){...
阅读全文
摘要:public class Solution { public double pow(double x, int n) { if(n<0){ return 1.0/powHelper(x,n); }else{ return powHelper(x, n); } } public double powHelper(double x, int n){ if(n == 0){ return 1; } double...
阅读全文
摘要: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].遍历list,将每个interval插入到result中去insert interval : http://www.cnblogs.com/RazerLu/p/3532267.html/** * Definition for an interval. * public class Interval { * int st...
阅读全文
摘要: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 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.ref:http://www.cnblogs.com/AnnieKim/archive/2013/04/21/3034631.html虽然不能再另外开辟非常数级的额外空间,但是可以在输入数组上就地进行swap操作。思路:交换数
阅读全文
摘要:public class Solution { public int atoi(String str) { if(str.length() == 0 || str == null){ return 0; } str = str.trim(); boolean positiveflag = true; if(str.charAt(0) == '+'){ str = str.substring(1); }else if(str.cha...
阅读全文
摘要: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
阅读全文
摘要:public class Solution { public double findMedianSortedArrays(int A[], int B[]) { int aLen = A.length; int bLen = B.length; if((aLen+bLen) % 2 == 0){ return (getKthElement(A, 0, aLen-1, B, 0, bLen-1, (aLen+bLen)/2) ...
阅读全文

浙公网安备 33010602011771号