LeetCode刷题
Seth_Lin
这个作者很懒,什么都没留下…
展开
-
find maximized count of 0 on left and 1 on right in binary array
给定一个 array,只包含 0,1, 找到一个分割位置,使左侧 0 出现的个数和右侧 1 出现的个数之和最 大化brute force, time: O(n^2), space: O(1) follow up, can we solve in O(n): DP, two temp array-google 1point3acres follow up, can we use O(1) spac转载 2015-09-17 00:48:19 · 328 阅读 · 0 评论 -
Greatest common divider
static int gcd(int a, int b){ if(a == 0 || b == 0) return a+b; // base case return gcd(b,a%b);}转载 2015-09-01 11:54:39 · 319 阅读 · 0 评论 -
[LeetCode]Word Break
https://leetcode.com/problems/word-break/Got the solution from here http://blog.csdn.net/linhuanmars/article/details/22358863. Quite clever. Interestingly it kind of use the similar approach from a que原创 2015-04-09 11:15:28 · 435 阅读 · 0 评论 -
Java regular expression regex
http://www.tutorialspoint.com/java/java_regular_expressions.htm原创 2015-04-08 05:35:02 · 364 阅读 · 0 评论 -
[LinkedIn] Word Distance Finder (Find distance in dictionary)
Example:WordDistanceFinder finder = new WordDistanceFinder(Arrays.asList(“the”, “quick”, “brown”, “fox”, “quick”));assert(finder.distance(“fox”,”the”) == 3);assert(finder.distance(“quick”, “fox”) == 1)原创 2015-04-02 04:05:46 · 1794 阅读 · 0 评论 -
Lowest/first common ancestor
public interface FirstCommonAncestor { /** * Given two nodes of a tree, * method should return the deepest common ancestor of those nodes. * * A * / \ * B C * / \ \ * D E M * / \原创 2015-04-08 01:06:08 · 555 阅读 · 0 评论 -
[Well..]Merge Sort implementation
//Code from: https://www.cs.cmu.edu/~adamchik/15-121/lectures/Sorting%20Algorithms/code/MergeSort.javaimport java.util.*;public class MergerSort{ public static void main(String[] args) {原创 2015-04-07 11:47:00 · 288 阅读 · 0 评论 -
[LeetCode] Permutations (Find all permutations of a integer array w/ or w/o duplicates)
/**Solution 1, using recursion. Construct a list of numbers by maintaining what you have now and what is left. Every level you take one element from the current "rest" array and append it to "cur"*原创 2015-04-03 10:39:16 · 312 阅读 · 0 评论 -
[LinkedIn] Array of size n and an int k, find all elements that appear/occur more than n/k times
A great answer from here :http://www.geeksforgeeks.org/given-an-array-of-of-size-n-finds-all-the-elements-that-appear-more-than-nk-times/Following is an interesting O(nk) solution: We can solve the ab原创 2015-04-07 00:34:52 · 692 阅读 · 0 评论 -
[LinkedIn] Smallest character that is strictly larger than the search character target
/** * Return the smallest character that is strictly larger than the search character, * If no such character exists, return the smallest character in the array * @param sortedStr : sorted list of l原创 2015-04-07 04:23:44 · 1410 阅读 · 1 评论 -
Flowerbed can place flowers problem
/* Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both原创 2015-04-07 14:41:56 · 1668 阅读 · 0 评论 -
[LinkedIn] Smallest/greatest/largest k element in stream of data (integer array) priority Q / heap
//This is for smallest//for largest, use min heap int[] getTopK (int[] input, int k) { if (k <= input.length) return input; PriorityQueue<Integer> q = new PriorityQueue<>(k, new Comparato原创 2015-04-07 12:30:17 · 907 阅读 · 0 评论 -
find path/route in a maze 2 d matrix
http://www.geeksforgeeks.org/backttracking-set-2-rat-in-a-maze/#include<stdio.h>#include <stdbool.h>// Maze size#define N 4 void printSolution(int sol[N][N]){ int i, j; for (i = 0; i < N; i+转载 2015-09-01 12:17:37 · 332 阅读 · 0 评论 -
[Amazon ]去元音 get rid of vowels
去元音: http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=105773&extra=page%3D1%26filter%3Dsortid%26sortid%3D311%26sortid%3D311//string 是题目给的字符串StringBuffer sb = new StringBuffer();String v转载 2015-08-21 03:24:01 · 1090 阅读 · 0 评论 -
[Amazon]Given 2 numbers. Find if they are consecutive gray (grey) code sequences
http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=105773&extra=page%3D1%26filter%3Dsortid%26sortid%3D311%26sortid%3D311//term1和term2是题目给的两个BYTEbyte x = (byte)(term1 ^ term2);int total = 0;转载 2015-08-21 03:33:07 · 1007 阅读 · 0 评论 -
missing ranges of sorted integer array
大自然的搬运工:http://www.danielbit.com/blog/puzzle/leetcode/leetcode-missing-ranges Given a sorted integer array where the range of elements are [0, 99] inclusive, return its missing ranges. For example, g转载 2015-09-17 00:53:29 · 331 阅读 · 0 评论 -
wiggle sort Given a list of integers, sort them so the output is s1 <= s2 >=s3 <=s4 ... sN.
每个元素和后一个元素比较看是不是希望的次序,如果不是的话互换就好public void wiggle_sort(int[] arr) { int n = arr.length; if(n <= 1) return; boolean inc = true; int prev = arr[0]; for(int i=1; i<n; i++) {转载 2015-09-17 00:18:54 · 479 阅读 · 0 评论 -
Reservoir Sampling (a random element from indefinite length stream with same probability)
Reservoir Sampling Reservoir sampling is a family of randomized algorithms for randomly choosing k samples from a list of n items, where n is either a very large or unknown number. Typically n is larg转载 2015-09-17 00:07:01 · 556 阅读 · 0 评论 -
serialize a list of string and deserialize it
import java.util.*;public class combineStrings{ public static void main(String[] args) { String[] arr = {"abc%cde", "a#aa", "haha"}; for(String s : arr) {转载 2015-09-17 00:46:41 · 333 阅读 · 0 评论 -
longest increasing continuous subsequence in a 2D matrix
dp + dfs //These two are only for traversing around x,y public int[] xMove = { 1, 0, 0, -1 }; public int[] yMove = { 0, 1, -1, 0 }; public int longestIncreasingContinuousSubsequenceII(int转载 2015-09-17 02:16:48 · 439 阅读 · 0 评论 -
perfect squares find the least number of perfect square numbers (1, 4, 9, 16, ...) which sum to n
用动态规划Dynamic Programming来做,我们建立一个长度为n+1的一维dp数组,将第一个值初始化为0,其余值都初始化为INT_MAX, i从0循环到n,j从1循环到i+j*j <= n的位置,然后每次更新dp[i+j*j]的值,动态更新dp数组,其中dp[i]表示正整数i能少能由多个完全平方数组成,那么我们求n,就是返回dp[n]即可,也就是dp数组的最后一个数字,参见代码如下:int转载 2015-09-17 02:01:21 · 551 阅读 · 0 评论 -
different/Unique/distinct Binary Search Trees
Given n, how many structurally unique BST's (binary search trees) that store values 1...n?For example,Given n = 3, there are a total of 5 unique BST's. 1 3 3 2 1 \ /转载 2015-09-16 15:24:05 · 652 阅读 · 0 评论 -
calculate sorted y of function y = ax^2 + bx + c given sorted x array
给定一个一元二次方程式y = ax^2 + bx + c, 一个sorted array X, 将X中所有元素代入方程中,返回sorted的Ysolution: 看a< or > 0,,搞出两边的y们,然后mergepublic class Ax2 { public static void main(String[] args) { } // x is sorted array转载 2015-09-16 15:42:31 · 599 阅读 · 0 评论 -
rotate matrix m*n
rotate a m*n matrix, not in place:void rotate(int row int col, int arr[][row],int rot_arr[][col]){ for(int j = 1; j < row; j++) { for (int i = m-1 , k = 0; i >= 0, k < m; i--, k++)转载 2015-09-14 09:31:39 · 285 阅读 · 0 评论 -
find duplicates in matrix within k indices
import java.util.*;public class find_dupicates_within_k_indices { static class Pos { int row; int col; Pos(int row, int col) { this.row = row; this.转载 2015-09-14 09:39:59 · 437 阅读 · 0 评论 -
[Amazon] Find loop in a singly linkedlist
As the title sayshttp://stackoverflow.com/questions/2663115/how-to-detect-a-loop-in-a-linked-list Floyd’s cycle-finding algorithm Having a fast and slow pointerboolean hasLoop(Node first) { if(f转载 2015-08-21 02:21:06 · 468 阅读 · 0 评论 -
[LeetCode] Construct/build binary tree from in-order and post-order/pre-order traversal
解答从这儿来:http://blog.csdn.net/linhuanmars/article/details/24390157 和 http://blog.csdn.net/linhuanmars/article/details/24389549in-order 和 pre-order 假设树的先序遍历是12453687,中序遍历是42516837。这里最重要的一点就是先序遍历可以提供根的所原创 2015-04-07 11:23:46 · 558 阅读 · 0 评论 -
[linkedin] flatten a doubly multi level linked list
Problem From Here: http://www.geeksforgeeks.org/flatten-a-linked-list-with-next-and-child-pointers/ Given a linked list where in addition to the next pointer, each node has a child pointer, which may原创 2015-04-07 10:50:48 · 786 阅读 · 0 评论 -
[LeetCode] Maximum path sum
From Here For each node, 4 conditions: 1. Node only (因为本题中的节点可能是负值!) 2. L-sub + Node 3. R-sub + Node 4. L-sub + Node + R-sub (in here the max value cannot be passed to the parent)public static int原创 2015-04-01 13:37:55 · 274 阅读 · 0 评论 -
[LinkedIn] String Permutation
print all permutation of strings From Herepublic static void permutation(String str) { permutation("", str); }private static void permutation(String prefix, String str) { int n = str.length(原创 2015-04-02 04:23:36 · 415 阅读 · 0 评论 -
[LeetCode刷题]Binary Tree Level Order Traversal
看到LinkedIn有考这道题目,就做了一下。 没什么特别的,在queue里面加了一个null来表示是在当前level的尽头/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(i原创 2015-03-30 05:17:31 · 281 阅读 · 0 评论 -
[LeetCode]Permutation sequence
From Here 数学找规律public String getPermutation(int n, int k) { if(n<=0) return ""; k--; StringBuilder res = new StringBuilder(); int factorial = 1; ArrayList<Integ原创 2015-03-31 14:22:45 · 260 阅读 · 0 评论 -
[LeetCode] Valid Number
这里看来的好的解答public boolean isNumber(String s) { if(s.trim().isEmpty()){ return false; } /* re* Matches 0 or more occurrences of preceding expression.原创 2015-03-30 23:50:09 · 362 阅读 · 0 评论 -
[LeetCode] clone graph
/** * Definition for undirected graph. * class UndirectedGraphNode { * int label; * List<UndirectedGraphNode> neighbors; * UndirectedGraphNode(int x) { label = x; neighbors = new Array原创 2015-03-31 14:45:02 · 304 阅读 · 0 评论 -
[LeetCode] Combination Sum
据说linkedin会考。。。没啥难的倒是public class Solution { public List<List<Integer>> combinationSum2(int[] num, int target) { Arrays.sort(num); List<List<Integer>> ret = new ArrayList<List<Integ原创 2015-03-31 14:12:07 · 247 阅读 · 0 评论 -
[LeetCode]Min Stack
implement Stack, getMin() is always O(1)class MinStack { LinkedList<Integer> main = new LinkedList<Integer>(); LinkedList<Integer> min = new LinkedList<Integer>(); public void push(int x) {原创 2015-03-31 01:18:02 · 248 阅读 · 0 评论 -
[LeetCode] Maxium Subarray
dynamic programming 的一道题。curMax是包括当前元素的subarray的max, gloMax是当前元素之前的整个array的maxpublic class Solution { public int maxSubArray(int[] A) { if(A.length == 1) { return A[0];原创 2015-03-31 00:25:03 · 207 阅读 · 0 评论 -
[LeetCode] Pow(x,n) O(logN)
又一个Linkedin面试过的public class Solution { public double pow(double x, int n) { int sign = 1; if(n < 0) { n = -n; sign = -1; } if(n == 0) return原创 2015-03-31 00:01:11 · 349 阅读 · 0 评论 -
[LeetCode刷题] Binary Tree Inorder Traversal
今天自己写了一下inorder traversal,写了一个挺neat的solution,感觉不错/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val =原创 2015-03-29 13:12:18 · 308 阅读 · 0 评论 -
[LeetCode] Search for a Range (sorted integers array,find start & end position of a target number)
/**O(n)的解法,从左到右遍历。**/public class Solution { public int[] searchRange(int[] A, int target) { if(A.length == 0) { return new int[]{-1,-1}; } int i = -1, j = -1原创 2015-04-03 10:01:40 · 419 阅读 · 0 评论