02 2014 档案

摘要:1 public static ListNode add(ListNode l1, ListNode l2){ 2 3 Stack s1 = new Stack(); 4 Stack s2 = new Stack(); 5 while(l1!=null){ 6 s1.push(l1.val); 7 l1 = l1.next; 8 } 9 while(l2!=null){10 s2.push(l2.val);11 ... 阅读全文
posted @ 2014-02-26 02:49 krunning 编辑
摘要:1 public static boolean(ListNode l1,ListNode l2){ 2 boolean res = false; 3 int [] check = {-1}; 4 ListNode mid = getMid(head,check); 5 if( check[0]==1){ 6 ListNode next = mid.next; 7 ListNode newHead =reverse(next); 8 res=checkPalidrom(head, newHead ); 9 newHead =re... 阅读全文
posted @ 2014-02-26 02:47 krunning 编辑
摘要:Given two words (startandend), and a dictionary, find all shortest transformation sequence(s) fromstarttoend, such that:Only one letter can be changed at a timeEach intermediate word must exist in the dictionaryFor example,Given:start="hit"end="cog"dict=["hot","dot 阅读全文
posted @ 2014-02-24 05:01 krunning 编辑
摘要: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.F... 阅读全文
posted @ 2014-02-24 04:56 krunning 编辑
摘要:1 public class Solution { 2 public ListNode insertionSortList(ListNode head) { 3 if(head==null) return head; 4 ListNode safe = new ListNode(Integer.MIN_VALUE); 5 ListNode p2 = head; 6 while(p2!=null){ 7 ListNode pre = find(safe,p2); 8 List... 阅读全文
posted @ 2014-02-24 04:53 krunning 编辑
摘要:1 public class Solution { 2 public ListNode sortList(ListNode head) { 3 if(head==null || head.next==null) return head; 4 ListNode fast = head, slow = head; 5 while(true){ 6 fast = fast.next; 7 if(fast==null) break; 8 fast = fast.next; ... 阅读全文
posted @ 2014-02-24 04:50 krunning 编辑
摘要:1 public class Solution { 2 public int maxPoints(Point[] points) { 3 HashMap map = new HashMap(); 4 int res = 0; 5 for(int i=0;i<points.length;i++){ 6 map.clear(); 7 int curMax = 1; 8 int sameP =0; 9 for(int j=i+1;j<points.... 阅读全文
posted @ 2014-02-24 04:06 krunning 编辑
摘要:Clone an undirected graph. Each node in the graph contains alabeland a list of itsneighbors. 1 public class Solution { 2 public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { 3 if(node==null) return node; 4 UndirectedGraphNode n1 = new UndirectedGraphNode(node.label);... 阅读全文
posted @ 2014-02-24 03:59 krunning 编辑
摘要:There areNgas stations along a circular route, where the amount of gas at stationiisgas[i].You have a car with an unlimited gas tank and it costscost[i]of gas to travel from stationito its next station (i+1). You begin the journey with an empty tank at one of the gas stations.Return the starting gas 阅读全文
posted @ 2014-02-24 03:45 krunning 编辑
摘要:1 public class Solution { 2 public int evalRPN(String[] tokens) { 3 String operations ="+-*/"; 4 Stack stack = new Stack(); 5 for(String s:tokens){ 6 if(!operations.contains(s)){ 7 stack.push(s); 8 } 9 else{10 ... 阅读全文
posted @ 2014-02-24 03:44 krunning 编辑
摘要:Given a singly linked listL:L0→L1→…→Ln-1→Ln,reorder it to:L0→Ln→L1→Ln-1→L2→Ln-2→…You must do this in-place without altering the nodes' values.For example,Given{1,2,3,4}, reorder it to{1,4,2,3}. 1 public class Solution { 2 public void reorderList(ListNode head) { 3 if(head==null) return; ... 阅读全文
posted @ 2014-02-22 16:23 krunning 编辑
摘要:1 public class LRUCache { 2 HashMap ht; 3 int curSize; 4 int size; 5 entry first=null; 6 entry last=null; 7 public LRUCache(int capacity) { 8 size = capacity; 9 ht = new HashMap();10 curSize = 0;11 }12 13 public int get(int key) {14 ... 阅读全文
posted @ 2014-02-22 16:20 krunning 编辑
摘要:public class Solution { public int singleNumber(int[] A) { int left = A[0]; for(int i=1;i<A.length;i++){ left ^=A[i]; } return left; }} 阅读全文
posted @ 2014-02-22 13:25 krunning 编辑
摘要:Given 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 "bbbbb" the longest substring is "b", with the length of 1. 阅读全文
posted @ 2014-02-22 13:21 krunning 编辑
摘要:Given a stringsand a dictionary of wordsdict, determine ifscan be segmented into a space-separated sequence of one or more dictionary words.For example, givens="leetcode",dict=["leet", "code"].Return true because"leetcode"can be segmented as"leet code&quo 阅读全文
posted @ 2014-02-22 13:13 krunning 编辑
摘要:Givennnon-negative integersa1,a2, ...,an, where each represents a point at coordinate (i,ai).nvertical lines are drawn such that the two endpoints of lineiis at (i,ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.Note: You 阅读全文
posted @ 2014-02-22 13:12 krunning 编辑
摘要: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],] 1 p... 阅读全文
posted @ 2014-02-22 13:11 krunning 编辑
摘要: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). 1 public class Solution { 2 ... 阅读全文
posted @ 2014-02-22 13:10 krunning 编辑
摘要:1 public class Solution { 2 public ListNode detectCycle(ListNode head) { 3 if(head==null) return head; 4 ListNode fast = head; 5 ListNode slow = head; 6 while(fast!=null){ 7 slow = slow.next; 8 fast = fast.next; 9 if(fast!=null... 阅读全文
posted @ 2014-02-22 13:09 krunning 编辑
摘要:Given a linked list, determine if it has a cycle in it. 1 public class Solution { 2 public boolean hasCycle(ListNode head) { 3 if(head==null) return false; 4 ListNode fast = head; 5 ListNode slow = head; 6 while(fast!=null){ 7 slow = slow.next; 8 ... 阅读全文
posted @ 2014-02-22 13:08 krunning 编辑
摘要:Given a stringsand a dictionary of wordsdict, add spaces insto construct a sentence where each word is a valid dictionary word.Return all such possible sentences.For example, givens="catsanddog",dict=["cat", "cats", "and", "sand", "dog"].A 阅读全文
posted @ 2014-02-22 13:07 krunning 编辑
摘要:Given an array of integers, every element appearsthreetimes except for one. Find that single one. 1 public class Solution { 2 public int singleNumber(int[] A) { 3 int bit [] = new int[32]; 4 for(int i=0;i>j; 7 if(rotate==0) break; 8 else bit[j] += ... 阅读全文
posted @ 2014-02-22 13:06 krunning 编辑
摘要:There areNchildren standing in a line. Each child is assigned a rating value.You are giving candies to these children subjected to the following requirements:Each child must have at least one candy.Children with a higher rating get more candies than their neighbors. 1 public class Solution { 2 p... 阅读全文
posted @ 2014-02-22 13:05 krunning 编辑
摘要:A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. 1 public class Solution { 2 public RandomListNode copyRandomList(RandomListNode head) { 3 if(head==null) return head; 4 //insert 5 RandomLis... 阅读全文
posted @ 2014-02-22 13:04 krunning 编辑
摘要: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. 1 public class Solution { 2 public int maxProfit(int[]... 阅读全文
posted @ 2014-02-19 05:33 krunning 编辑
摘要:1 public class Solution { 2 public ArrayList preorderTraversal(TreeNode root) { 3 ArrayList res = new ArrayList(); 4 if(root==null) return res; 5 TreeNode cur = root; 6 Stackstack = new Stack(); 7 while(!stack.isEmpty() || cur!=null){ 8 if(cur!... 阅读全文
posted @ 2014-02-19 05:31 krunning 编辑
摘要: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. 1 public class Solution { 2 public int maxProfit(int[] prices) { 3 int len = prices.length; 4 if(len==0) re... 阅读全文
posted @ 2014-02-19 05:30 krunning 编辑
摘要: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 public class Solution { 2 ... 阅读全文
posted @ 2014-02-19 05:29 krunning 编辑
摘要: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 阅读全文
posted @ 2014-02-19 05:27 krunning 编辑
摘要:Given an absolute path for a file (Unix-style), simplify it.For example,path="/home/", =>"/home"path="/a/./b/../../c/", =>"/c"Did you consider the case wherepath="/../"?In this case, you should return"/".Another corner case is the pat 阅读全文
posted @ 2014-02-19 05:26 krunning 编辑
摘要:1 public class Solution { 2 public ArrayList postorderTraversal(TreeNode root) { 3 ArrayList res = new ArrayList(); 4 if(root==null) return res; 5 TreeNode cur = null, pre = null; 6 Stackstack = new Stack(); 7 stack.push(root); 8 while(!stack.isEm... 阅读全文
posted @ 2014-02-19 05:25 krunning 编辑
摘要: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 / / \ ... 阅读全文
posted @ 2014-02-19 00:38 krunning 编辑
摘要: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? 1 public class Solution { 2 public ArrayList getRow(int rowIndex) { 3 ArrayList res = new ArrayList(); 4 int num [... 阅读全文
posted @ 2014-02-19 00:32 krunning 编辑
摘要:Given an arraySofnintegers, find three integers inSsuch that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to ... 阅读全文
posted @ 2014-02-19 00:30 krunning 编辑
摘要: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 阅读全文
posted @ 2014-02-19 00:28 krunning 编辑
摘要: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 ... 阅读全文
posted @ 2014-02-19 00:27 krunning 编辑
摘要: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", " 阅读全文
posted @ 2014-02-19 00:26 krunning 编辑
摘要: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]] 1 public class Solution { 2 public ArrayList> generate(int numRows) { 3 ArrayList> res = new ArrayList>(); 4 if(numRows==0) retu... 阅读全文
posted @ 2014-02-19 00:25 krunning 编辑
摘要: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. 1 public class Solution { 2 public ListNode rotateRight(ListNode head, int n) { 3 if(head==null || n==0) return head; 4 int 阅读全文
posted @ 2014-02-17 05:50 krunning 编辑
摘要: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" 阅读全文
posted @ 2014-02-17 02:18 krunning 编辑
摘要: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 ]] 1 public class Solution { 2 public int[][] generateMatrix(int n) { 3 int []count = {1}; 4 ... 阅读全文
posted @ 2014-02-17 02:16 krunning 编辑
摘要: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]... 阅读全文
posted @ 2014-02-17 02:15 krunning 编辑
摘要: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. 1 public class Solution { 2 public ListNode reverseBe 阅读全文
posted @ 2014-02-17 02:14 krunning 编辑
摘要: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?For example,Given the following binary tree, 1 / \ 2 3 / \ \ 4 5 7After calling your function, the tree s... 阅读全文
posted @ 2014-02-17 02:07 krunning 编辑
摘要:Given a binary tree, find the maximum path sum.The path may start and end at any node in the tree.For example:Given the below binary tree, 1 / \ 2 3 Return6. 1 public class Solution { 2 public int maxPathSum(TreeNode root) { 3 int res []={Integer.MIN_VALUE}; 4 he... 阅读全文
posted @ 2014-02-17 01:46 krunning 编辑
摘要:The 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"Write the code that will take a string and 阅读全文
posted @ 2014-02-17 01:44 krunning 编辑
摘要:1 public class Solution { 2 public String longestCommonPrefix(String[] strs) { 3 int len = strs.length; 4 if(len<=0) return ""; 5 if(len==1) return strs[0]; 6 String pre = strs[0]; 7 for(int i=1;i<len;i++){ 8 String cur = strs[i]; 9 ... 阅读全文
posted @ 2014-02-17 01:43 krunning 编辑
摘要:Two elements of a binary search tree (BST) are swapped by mistake.Recover the tree without changing its structure. 1 public class Solution { 2 public void recoverTree(TreeNode root) { 3 if(root==null) return ; 4 ArrayList t = new ArrayList (); 5 ArrayList v = new ArrayLis... 阅读全文
posted @ 2014-02-17 01:40 krunning 编辑
摘要: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. 1 阅读全文
posted @ 2014-02-13 04:51 krunning 编辑
摘要:Given a collection of integers that might contain duplicates,S, return all possible subsets.IfS=[1,2,2], a solution is:[ [2], [1], [1,2,2], [2,2], [1,2], []] 1 public class Solution{ 2 public ArrayList> subsetsWithDup(int[] num) { 3 Arrays.sort(num); 4 ArrayList> res = new Arra... 阅读全文
posted @ 2014-02-13 04:28 krunning 编辑
摘要:1 public class Solution { 2 public ArrayList> fourSum(int[] num, int target) { 3 ArrayList> res = new ArrayList>(); 4 int len = num.length; 5 if(len temp = new ArrayList();15 temp.add(num[i]);16 temp.add(num[j]);17 ... 阅读全文
posted @ 2014-02-13 04:27 krunning 编辑
摘要:Follow up for "Remove Duplicates":What if duplicates are allowed at mosttwice? 1 public class Solution { 2 public int removeDuplicates(int[] A) { 3 int len = A.length; 4 if(len<=2) return len; 5 int count = 1; 6 int p1 =1, p2=1; 7 while(p2<len){ 8 ... 阅读全文
posted @ 2014-02-13 04:26 krunning 编辑
摘要:1 public class Solution { 2 public ArrayList grayCode(int n) { 3 ArrayList res = new ArrayList(); 4 res.add(0); 5 for(int i=0;i=0;j--){ 9 res.add(highest+res.get(j));10 }11 }12 return res;13 }14 }View Code 阅读全文
posted @ 2014-02-13 04:25 krunning 编辑
摘要:1 public class Solution { 2 public TreeNode buildTree(int[] inorder, int[] postorder) { 3 int inEnd = inorder.length-1; 4 int postEnd = postorder.length-1; 5 if(inEnd0)19 root.left = build(in,inStart,piv-1,post,postStart,postStart+leftLen-1);20 if(piv... 阅读全文
posted @ 2014-02-12 04:08 krunning 编辑
摘要:1 public class Solution { 2 public TreeNode buildTree(int[] preorder, int[] inorder) { 3 int len =preorder.length; 4 if(lenpreE || inS>inE) return null; 9 int first = pre[preS];10 TreeNode p = new TreeNode(first);11 if(preS==preE) // don't forget this12 ... 阅读全文
posted @ 2014-02-12 04:01 krunning 编辑
摘要:1 public class Solution { 2 public String countAndSay(int n) { 3 String res = "1"; 4 if(n==0) return res; 5 for(int i=1;i1){22 temp = temp+count+last;23 count = 1;24 }25 else{26 temp = temp+c... 阅读全文
posted @ 2014-02-12 04:01 krunning 编辑
摘要: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". 1 public class Solution { 2 public String minWindow(String S, String T) { 3 int sLen 阅读全文
posted @ 2014-02-12 03:58 krunning 编辑
摘要: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. 1 public class Solution { 2 publ... 阅读全文
posted @ 2014-02-12 03:56 krunning 编辑
摘要:The Sudoku board could be partially filled, where empty cells are filled with the character'.'. 1 public class Solution { 2 public boolean isValidSudoku(char[][] board) { 3 for(int i=0;i<9;i++){ 4 int []row = new int[10]; 5 int []col = new int[10]; 6 f... 阅读全文
posted @ 2014-02-10 15:33 krunning 编辑
摘要:Given 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) 1 public class Solution { 2 public ArrayList restoreIpAddresses(S 阅读全文
posted @ 2014-02-10 15:32 krunning 编辑
摘要: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- 阅读全文
posted @ 2014-02-10 15:31 krunning 编辑
摘要: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 阅读全文
posted @ 2014-02-10 15:30 krunning 编辑
摘要: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 ... 阅读全文
posted @ 2014-02-10 15:29 krunning 编辑
摘要:You are given annxn2D matrix representing an image.Rotate the image by 90 degrees (clockwise).Follow up:Could you do this in-place? 1 public class Solution { 2 public void rotate(int[][] matrix) { 3 int len = matrix.length; 4 if(len<=0) return; 5 for(int i=0;i<len-1;i++){... 阅读全文
posted @ 2014-02-08 05:53 krunning 编辑
摘要: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 1 public class So 阅读全文
posted @ 2014-02-08 04:48 krunning 编辑
摘要: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.[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, ... 阅读全文
posted @ 2014-02-08 04:32 krunning 编辑
摘要: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]. 1 public class Solution { 2 public ArrayList> permuteUnique(int[] num) { 3 ArrayList> res = new Arra... 阅读全文
posted @ 2014-02-08 04:30 krunning 编辑
摘要:Given amxngrid filled with non-negative numbers, find a path from top left to bottom right whichminimizesthe sum of all numbers along its path. 1 public class Solution { 2 public int minPathSum(int[][] grid) { 3 int len1 = grid.length; 4 if(len1==0) return 0; 5 int len2 =... 阅读全文
posted @ 2014-02-07 03:52 krunning 编辑
摘要:Determine whether an integer is a palindrome. Do this without extra space. 1 public class Solution { 2 public boolean isPalindrome(int x) { 3 if(x=10){ 6 div *=10; 7 } 8 while(x>0){ 9 if(x/div!=x%10) return false;10 x = x%div/10;11 ... 阅读全文
posted @ 2014-02-07 03:49 krunning 编辑
摘要:There is one obstacle in the middle of a 3x3 grid as illustrated below.[ [0,0,0], [0,1,0], [0,0,0]] 1 public class Solution { 2 public int uniquePathsWithObstacles(int[][] obstacleGrid) { 3 int len = obstacleGrid.length; 4 if(len==0) return 0; 5 int len2 = obstacleGrid... 阅读全文
posted @ 2014-02-07 03:48 krunning 编辑
摘要: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 阅读全文
posted @ 2014-02-07 03:47 krunning 编辑
摘要: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 阅读全文
posted @ 2014-02-07 03:46 krunning 编辑
摘要: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], ... 阅读全文
posted @ 2014-02-06 15:31 krunning 编辑
摘要:1 public class Solution { 2 public boolean isSameTree(TreeNode p, TreeNode q) { 3 if(p==null) return q==null; 4 if(q==null) return p==null; 5 if(p.val==q.val){ 6 return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right); 7 } 8 else return ... 阅读全文
posted @ 2014-02-06 15:22 krunning 编辑
摘要:1 public class Solution { 2 public boolean isBalanced(TreeNode root) { 3 if(root==null) return true; 4 if(checkHeight(root)==-1) return false; 5 return true; 6 } 7 public int checkHeight(TreeNode root){ 8 if(root==null) return 0; 9 int left = chec... 阅读全文
posted @ 2014-02-06 15:20 krunning 编辑
摘要: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. 1 public class Solution { 2 public boolean isInterleave(String s1, String s2, Strin 阅读全文
posted @ 2014-02-06 15:18 krunning 编辑
摘要:A 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 message"12", it cou 阅读全文
posted @ 2014-02-06 15:14 krunning 编辑
摘要: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 XX X O XX O X XAfter running your function, the board should be:X X X XX X X XX X X 阅读全文
posted @ 2014-02-06 15:06 krunning 编辑
摘要:Given two words (startandend), and a dictionary, find the length of shortest transformation sequence fromstarttoend, such that:Only one letter can be changed at a timeEach intermediate word must exist in the dictionaryFor example,Given:start="hit"end="cog"dict=["hot",&q 阅读全文
posted @ 2014-02-06 15:05 krunning 编辑
摘要: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. 1 public class Solution { 2 public boolean isPalindrome(String s) { 3 int len = 阅读全文
posted @ 2014-02-06 15:04 krunning 编辑
摘要: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. 1 public class Solution { 2 public... 阅读全文
posted @ 2014-02-06 15:03 krunning 编辑
摘要: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 阅读全文
posted @ 2014-02-06 15:02 krunning 编辑
摘要: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"] ] 1 public class Solution { 2 public ArrayLis 阅读全文
posted @ 2014-02-06 15:01 krunning 编辑
摘要: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. 1 public cla 阅读全文
posted @ 2014-02-06 15:00 krunning 编辑
摘要:1 public class Solution { 2 public ArrayList inorderTraversal(TreeNode root) { 3 ArrayList res = new ArrayList (); 4 Stack stack = new Stack(); 5 TreeNode cur = root; 6 while(!stack.isEmpty()||cur!=null){ 7 if(cur!=null){ 8 stack.push(cur); 9 ... 阅读全文
posted @ 2014-02-06 14:59 krunning 编辑
摘要:1 public class Solution { 2 public int climbStairs(int n) { 3 int f1 = 2; 4 int f2 = 1; 5 if(n<=0) return 0; 6 if(n==1) return f2; 7 if(n==2) return f1; 8 int fn=0; 9 for(int i=2;i<n;i++){10 fn=f1+f2;11 f2=f1;12 f1=fn;13 }14 return fn;15 }16 }View Code 阅读全文
posted @ 2014-02-06 14:59 krunning 编辑
摘要:1 public class Solution { 2 public boolean isValidBST(TreeNode root) { 3 return is(root,Integer.MAX_VALUE,Integer.MIN_VALUE); 4 } 5 public boolean is(TreeNode root,int max,int min){ 6 if(root==null) 7 return true; 8 if(root.valmin){ 9 retur... 阅读全文
posted @ 2014-02-06 14:58 krunning 编辑
摘要: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 3 1 public class Solution { 2 public boolean isSymmetric(TreeNode... 阅读全文
posted @ 2014-02-06 14:57 krunning 编辑
摘要:1 public class Solution { 2 public ArrayList> levelOrder(TreeNode root) { 3 ArrayList> res = new ArrayList>(); 4 LinkedList cur = new LinkedList(); 5 if(root==null) return res; 6 cur.offer(root); 7 while(!cur.isEmpty()){ 8 LinkedList next = ne... 阅读全文
posted @ 2014-02-06 14:56 krunning 编辑
摘要:1 public class Solution {2 public int maxDepth(TreeNode root) {3 if(root==null)4 return 0;5 return Math.max(maxDepth(root.left),maxDepth(root.right))+1;6 }7 }View Code 阅读全文
posted @ 2014-02-06 14:55 krunning 编辑
摘要:Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 1 // We shuould use a static variable int the recursive function!!!! 2 public class Solution { 3 static ListNode h; 4 public TreeNode sortedListToBST(ListNode head) { 5... 阅读全文
posted @ 2014-02-06 14:54 krunning 编辑
摘要: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 public class Solution { 2 public int minDepth(TreeNode root) { 3 if(root==null) return 0; 4 int left = minDepth(root.le... 阅读全文
posted @ 2014-02-06 14:53 krunning 编辑
摘要: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 / \ ... 阅读全文
posted @ 2014-02-06 14:52 krunning 编辑
摘要:1 public class Solution { 2 public int sqrt(int x) { 3 if(x==0 ||x==1) return x; 4 long start = 1; 5 long end = x-1; 6 while(startx){11 end = mid-1;12 }13 else{14 start = mid+1;15 }16 }17 ... 阅读全文
posted @ 2014-02-06 14:51 krunning 编辑
摘要: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 ... 阅读全文
posted @ 2014-02-06 14:50 krunning 编辑
摘要:Given two sorted integer arrays A and B, merge B into A as one sorted array. 1 public class Solution { 2 public void merge(int A[], int m, int B[], int n) { 3 int p3 = m+n-1; 4 int p1 = m-1; 5 int p2 = n-1; 6 while(p1>=0 && p2>=0){ 7 if(A[p1]>=B[p2]){ ... 阅读全文
posted @ 2014-02-06 14:49 krunning 编辑
摘要: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... 阅读全文
posted @ 2014-02-06 14:48 krunning 编辑
摘要:Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area. 1 public class Solution { 2 public int maximalRectangle(char[][] matrix) { 3 int row = matrix.length; 4 if(row=0;j--){28 if(matrix[i][j]=='1'){29 ... 阅读全文
posted @ 2014-02-06 14:47 krunning 编辑
摘要: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. 1 public class Solution { 2 public ListNode deleteDu 阅读全文
posted @ 2014-02-06 14:45 krunning 编辑
摘要:1 public class Solution { 2 public void setZeroes(int[][] matrix) { 3 boolean row = false; 4 boolean col = false; 5 for(int i=0;i<matrix.length;i++){ 6 if(matrix[i][0]==0){ 7 row =true; 8 break; 9 }10 }11 ... 阅读全文
posted @ 2014-02-06 14:43 krunning 编辑
摘要:Given a sorted linked list, delete all duplicates such that each element appear onlyonce. 1 public class Solution { 2 public ListNode deleteDuplicates(ListNode head) { 3 ListNode cur =head; 4 while(cur!=null&&cur.next!=null){ 5 if(cur.val==cur.next.val){ 6 ... 阅读全文
posted @ 2014-02-06 14:42 krunning 编辑
摘要: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. 1 public class Solution { 2 public int largestRectangleArea(int[] height) { 3 int length = height.length; 4 if(leng... 阅读全文
posted @ 2014-02-06 14:41 krunning 编辑
摘要: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. 1 public class Solution { 2 //rotated array all is A[start]){10 if(target>=A[start] ... 阅读全文
posted @ 2014-02-06 14:40 krunning 编辑
摘要: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 阅读全文
posted @ 2014-02-06 14:39 krunning 编辑
摘要: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 ArrayList> res = new ArrayList>(); 4 ... 阅读全文
posted @ 2014-02-06 14:38 krunning 编辑
摘要:1 public class Solution { 2 public int[] plusOne(int[] digits) { 3 int carry = 1; 4 for(int i=digits.length-1;i>=0;i--){ 5 digits[i] +=carry; 6 carry = digits[i]/10; 7 digits[i] %=10; 8 } 9 if(carry>0){10 int []num ... 阅读全文
posted @ 2014-02-06 14:37 krunning 编辑
摘要:1 public class Solution { // don't forget 'break' 'if(s.length()<=0) return false;' should be after trim 2 public boolean isNumber(String s) { 3 s = s.trim(); 4 if(s.length()<=0) return false; 5 boolean eFound = false; 6 boolean dFound = false; 7 int end ... 阅读全文
posted @ 2014-02-06 14:34 krunning 编辑
摘要: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 1 public class Solution { 2 public int mi... 阅读全文
posted @ 2014-02-06 14:33 krunning 编辑
摘要:1 public class Solution { 2 public String addBinary(String a, String b) { 3 int len1 = a.length(); 4 int len2 = b.length(); 5 StringBuilder sb = new StringBuilder(); 6 int p1 = len1-1; 7 int p2 = len2 -1; 8 int carry = 0; 9 while(p1>=0&&p2... 阅读全文
posted @ 2014-02-06 14:32 krunning 编辑
摘要:1 public class Solution { 2 public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 3 ListNode safe = new ListNode(-1); 4 ListNode pre = safe; 5 while(l1!=null && l2!=null){ 6 if(l1.val<l2.val){ 7 pre.next = l1; 8 l1 = l1.nex... 阅读全文
posted @ 2014-02-06 14:31 krunning 编辑
摘要: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 阅读全文
posted @ 2014-02-06 14:29 krunning 编辑
摘要: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]. 1 public class Solution { 2 public ArrayList merge(ArrayList intervals) { 3 if(intervals.size()==0) 4 return intervals; 5 6 ... 阅读全文
posted @ 2014-02-06 14:28 krunning 编辑
摘要: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. 1 阅读全文
posted @ 2014-02-06 14:27 krunning 编辑
摘要: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. 1 public class Solution { 2 public int lengthOfLastWord(String s) { 3 int len = s.length(); 4 int count=0; ... 阅读全文
posted @ 2014-02-06 14:24 krunning 编辑
摘要: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. 1 public class Solution { 2 public ArrayList insert(ArrayList intervals, Interval newInterval) { 3 ... 阅读全文
posted @ 2014-02-06 14:23 krunning 编辑
摘要:Now, instead outputting board configurations, return the total number of distinct solutions. 1 public class Solution { 2 public int totalNQueens(int n) { 3 int []total = new int [1]; 4 get(new int[n],0,n,total); 5 return total[0]; 6 } 7 public void get(int []queen... 阅读全文
posted @ 2014-02-06 14:21 krunning 编辑
摘要:1 public class Solution { 2 public ArrayList anagrams(String[] strs) { 3 int len = strs.length; 4 HashMap> hm = new HashMap>(); 5 ArrayList res = new ArrayList(); 6 for(int i=0;i temp = new ArrayList();13 temp.add(strs[i]);14 hm.pu... 阅读全文
posted @ 2014-02-06 14:20 krunning 编辑
摘要:public class Solution { public ArrayList solveNQueens(int n) { ArrayList res = new ArrayList(); dfs(n,0,new int[n],res); retur... 阅读全文
posted @ 2014-02-06 14:19 krunning 编辑
摘要:1 public class Solution { 2 public double pow(double x, int n) { 3 if(x==0||x==1) return x; 4 if(n<0)return 1/helper(x,-1*n); 5 else return helper(x,n); 6 } 7 public double helper(double x,int n){ 8 if(n==0) return 1; 9 double res = helper(x,n/2);... 阅读全文
posted @ 2014-02-06 14:18 krunning 编辑
摘要:Given two numbers represented as strings, return multiplication of the numbers as a string. 1 public class Solution { 2 public String multiply(String num1, String num2) { 3 if(num1.equals("0")||num2.equals("0")) return "0"; 4 int len1 = num1.length(); 5 int len2 = num2. 阅读全文
posted @ 2014-02-06 14:17 krunning 编辑
摘要: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> permute(int[] num) { 3 int len = num.length; 4 ArrayList> res = ne... 阅读全文
posted @ 2014-02-06 14:16 krunning 编辑
摘要: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 阅读全文
posted @ 2014-02-06 14:15 krunning 编辑
摘要: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. 1 public class Solution { 2 public ArrayList> combinationSum2(int[] candidates, int target) { 3 ... 阅读全文
posted @ 2014-02-06 14:13 krunning 编辑
摘要: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. 1 public class Solution { 2 public int firstMissingPositive(int[] A) { 3 if(A.length0){18 ... 阅读全文
posted @ 2014-02-06 14:13 krunning 编辑
摘要: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. 1 public class Solution { 2 public ArrayList> combinationSum(int[] candidates, int target) {... 阅读全文
posted @ 2014-02-06 14:12 krunning 编辑
摘要:Write a program to solve a Sudoku puzzle by filling the empty cells.Empty cells are indicated by the character'.'. 1 public class Solution { 2 public void solveSudoku(char[][] board) { 3 solve(board); 4 } 5 public boolean solve(char[][]board){ 6 for(int i=0;i<9;i++){ 7 ... 阅读全文
posted @ 2014-02-06 14:11 krunning 编辑
摘要: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 ord... 阅读全文
posted @ 2014-02-06 14:10 krunning 编辑
摘要:Suppose a sorted array is rotated at some pivot unknown to you beforehand. 1 public class Solution { 2 //all is equal in sorted array 3 public int search(int[] A, int target) { 4 if(A.length=A[start]){//don't forget the equal10 if(target=A[start]){11 ... 阅读全文
posted @ 2014-02-06 14:09 krunning 编辑
摘要: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 阅读全文
posted @ 2014-02-06 14:08 krunning 编辑
摘要: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 if(haystack==null) return null; 4 int len1= haystack.length(); 5 int len2 = needl... 阅读全文
posted @ 2014-02-06 14:07 krunning 编辑
摘要: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. 1 public class Solution { 2 public int maxSubArray(int[] A) { 3 if(A.length... 阅读全文
posted @ 2014-02-06 14:06 krunning 编辑
摘要:Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 1 public class Solution { 2 public TreeNode sortedArrayToBST(int[] num) { 3 if(num.length==0) return null; 4 return get(num,0,num.length-1); 5 } 6 public TreeNode get(int []n... 阅读全文
posted @ 2014-02-06 14:05 krunning 编辑
摘要: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. 1 public class Solution { 2 public int removeElement(int[] A, int elem) { 3 int p1 = 0; 4 ... 阅读全文
posted @ 2014-02-06 14:00 krunning 编辑
摘要: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 阅读全文
posted @ 2014-02-06 13:59 krunning 编辑
摘要: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 阅读全文
posted @ 2014-02-06 13:58 krunning 编辑
摘要:Divide two integers without using multiplication, division and mod operator. 1 public class Solution { 2 public int divide(int dividend, int divis... 阅读全文
posted @ 2014-02-06 05:41 krunning 编辑
摘要: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. 1 public class Solut 阅读全文
posted @ 2014-02-06 05:39 krunning 编辑
摘要:1 /* Min heap*/ 2 public class Solution { 3 public ListNode mergeKLists(ArrayList lists) { 4 if(lists.size() comparator = new Comparator(){ 7 public int compare(ListNode m,ListNode n){ 8 return m.val-n.val; 9 }10 };11 PriorityQueue... 阅读全文
posted @ 2014-02-06 05:37 krunning 编辑
摘要:Givennpairs of parentheses, write a function to generate all combinations of well-formed parentheses.For example, givenn= 3, a solution set is:"((()))", "(()())", "(())()", "()(())", "()()()" 1 public class Solution { 2 public ArrayList generateParen 阅读全文
posted @ 2014-02-06 05:35 krunning 编辑
摘要: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. 1 阅读全文
posted @ 2014-02-06 05:34 krunning 编辑
摘要:Given a linked list, remove thenthnode from the end of list and return its head. 1 public class Solution { 2 public ListNode removeNthFromEnd(ListNode head, int n) { 3 ListNode safe = new ListNode(-1); 4 safe.next = head; 5 ListNode p1 = safe; 6 for(int i=0;i<=n;i... 阅读全文
posted @ 2014-02-06 05:33 krunning 编辑
摘要:Given 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", "af", "bd", "be", &q 阅读全文
posted @ 2014-02-06 05:30 krunning 编辑
摘要:Given an arraySofnintegers, are there elementsa,b,cinSsuch thata+b+c= 0? Find all unique triplets in the array which gives the sum of zero. 1 public class Solution { 2 public ArrayList> threeSum(int[] num) { 3 ArrayList> res = new ArrayList>(); 4 if(num.lengthsum){16 ... 阅读全文
posted @ 2014-02-06 05:28 krunning 编辑
摘要:Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from 1 to 3999. 1 public class Solution { 2 public int romanToInt(String s) { 3 if(s.length()0 && get(s.charAt(i-1))<cur) 8 res += cur-2*get(s.charAt(i-1)); 9 else{10 ... 阅读全文
posted @ 2014-02-06 05:03 krunning 编辑
摘要:Given an integer, convert it to a roman numeral. 1 public class Solution { 2 public String intToRoman(int num) { 3 char[] sym = {'I','V','X','L','C','D','M'}; 4 int scale = 1000; 5 StringBuilder sb = new StringBuilder(); 6 for(int i=6;i>=0;i 阅读全文
posted @ 2014-02-06 05:01 krunning 编辑
摘要: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 阅读全文
posted @ 2014-02-06 04:59 krunning 编辑
摘要:Implementatoito convert a string to an integer. 1 public class Solution { 2 public int atoi(String str) { 3 char[] s = str.trim().toCharArray(); 4 if(s.length==0){ 5 return 0; 6 } 7 long num = 0; 8 int sign =1; 9 int len = s.length;10 ... 阅读全文
posted @ 2014-02-06 04:58 krunning 编辑
摘要:Reverse digits of an integer.Example1:x = 123, return 321Example2:x = -123, return -321 1 public class Solution { 2 public int reverse(int x) { 3 int sign = 1; 4 if(x0){ 9 res = 10*res+x%10;10 x /=10;11 }12 if(res<0) return -1;13 re... 阅读全文
posted @ 2014-02-06 04:57 krunning 编辑
摘要:Given a stringS, find the longest palindromic substring inS. You may assume that the maximum length ofSis 1000, and there exists one unique longest palindromic substring. 1 public class Solution { 2 public String longestPalindrome(String s) { 3 if(s.length()=0;i--){10 for(int... 阅读全文
posted @ 2014-02-06 04:55 krunning 编辑
摘要: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 digit. Add the two numbers and return it as a linked list.Input:(2 -> 4 -> 3) + (5 -> 6 -> 4)Output:7 -> 0 -> 8 1 public class Solut 阅读全文
posted @ 2014-02-06 04:53 krunning 编辑
摘要:There 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)). 1 public class Solution { 2 public double findMedianSortedArrays(int A[], int B[]) { 3 int len1 = A.length; 4 int le... 阅读全文
posted @ 2014-02-06 04:52 krunning 编辑
摘要:Given 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 answers (both index1 and index2) are 阅读全文
posted @ 2014-02-06 04:51 krunning 编辑