String to Integer (atoi) 这一题
通过的code是:
public class Solution {
public int myAtoi(String str) {
if (str == null || str.length() < 1)
return 0;
// trim white spaces
str = str.trim();
char flag = '+';
// check negative or positive
int i = 0;
if (str.charAt(0) == '-') {
flag = '-';
i++;
} else if (str.charAt(0) == '+') {
i++;
}
// use double to store result
double result = 0;
// calculate value
while... 阅读全帖
我写了一个,不知道可用不,先用DP找到最长subsequence的长度,complexity is O(
nlongn);
再用recursive找到所有可行解。
public static List> AllLongestIncreasingSubsequence(int[] nums
) {
int[] m = new int[nums.length + 1];
int L = 0;
for (int i = 0; i < nums.length; i++) {
int lo = 1;
int hi = L;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (nums[m[mid]] < nums[i]) lo = mid + 1;
else hi = mid - 1;
}... 阅读全帖
import java.util.*;
public class DesignDataStructure {
Map> map = new HashMap>();
List list = new ArrayList();
public void add(int num){
list.add(num);
int index=list.size()-1;
if(map.containsKey(num)){
map.get(num).add(index);
}else{
Set set =new HashSet();
set.add(index);
map.put(num, set);
}
}
public voi... 阅读全帖
import java.util.*;
public class DesignDataStructure {
Map> map = new HashMap>();
List list = new ArrayList();
public void add(int num){
list.add(num);
int index=list.size()-1;
if(map.containsKey(num)){
map.get(num).add(index);
}else{
Set set =new HashSet();
set.add(index);
map.put(num, set);
}
}
public voi... 阅读全帖
第一题的java答案抄了一个,运行通过的。 https://github.com/nagajyothi/InterviewBit/blob/master/DynamicProgramming/
AvgSet.java
各路大神看看还有没有更优解。
// Sum_of_Set1 / size_of_set1 = total_sum / total_size, and so, Sum_of_Set1
= size_of_set1 * total_sum / total_size.
// Now we can just iterate on size_of_set1, and we would know the required
Sum_of_Set1.
static List res = new ArrayList();
static boolean[][][] dp;
public static List> partitionAverage(int[] num) {
List阅读全帖
# Title Editorial Acceptance Difficulty Frequency
1
Two Sum 28.3% Easy
292
Nim Game 54.4% Easy
344
Reverse String 57.3% Easy
136
Single Number 52.2% Easy
2
Add Two Numbers 25.6% Medium
371
Sum of Two Integers 51.6% Easy
4
Median of Two Sorted Arrays
20.4% Hard
6
ZigZag Conversion 25.6% Easy
13
Roman to Integer 42.7% Easy
237
... 阅读全帖
下面是单线程,而且图是adjacency list
public class Solution {
//5763 ms, method: bfs, 时间O(N + E),空间O(N)。
public List> connectedSet(ArrayList
nodes) {
List> res = new ArrayList<>();
List path = new ArrayList<>();
Set visited = new HashSet<>();
for (UndirectedGraphNode node : nodes) {
if (!visited.contains(node)) {
path.clear();
Queue阅读全帖
A .txt file. Use the below java code to read the file and use a 2-D array (
one dimension for the users and other dimension for the products) to store
the order#. Also, use a dictionary to map each users to its corresponding
array row. How to replace the missing value with 0 in the 2D array?
Users, Products, order#:
name1 p1 5
name1 p2
name1 p3 2
name2 p1 3
name2 p2 1
name2 p3
name3 p1 5
name3 p2
name3 p3 2
name4 p1 3
name4... 阅读全帖
O(n) algorithm:
public Integer[] getMaxInSlideWindow(Integer[] A, Integer w) {
// invalid input
if (A == null || w <= 0 || A.length - w + 1 <= 0)
return null;
Integer[] B = new Integer[A.length - w + 1];
// auxiliary queue that is sorted in descending order
List q = new LinkedList();
for (int i = 0; i < A.length; i++) {
// enqueue. Remove those smaller values
int data = A[i];
whi... 阅读全帖
周五面完最后一个onsite, 累的惨兮兮的, 好容易爬回家. 不管结果如何, 这段时间找
工作算是告一段落了.
下面把这段时间面试中被问到的题目整理一下, 供大家参考. 我也就不说具体是那些公
司了, 都是很典型的面试题, 到哪里都有可能会被问到.
* implement memcpy? How to improve? how to determine if a system is
32bit or 64bit?
* how is static keyword used in Java?
* a list of intervals, no overlapping and sorted, write a function to
insert an interval into the list and still keep the list sorted and no
overlapping.
* given a function on sorted dictionary to retrieve word by index,
string getWord(int i), how to i... 阅读全帖
I am not sure what's your question. But as example, here is a simplified
Java implementation, assume sets no more than 32. If more than that, you can
use BigInteger or write your own class.
public class Subset {
public Set[] merge(Set[] sets) {
HashMap
☆─────────────────────────────────────☆
yuhanlin (Yuhan) 于 (Mon Aug 29 00:18:17 2011, 美东) 提到:
周五面完最后一个onsite, 累的惨兮兮的, 好容易爬回家. 不管结果如何, 这段时间找
工作算是告一段落了.
下面把这段时间面试中被问到的题目整理一下, 供大家参考. 我也就不说具体是那些公
司了, 都是很典型的面试题, 到哪里都有可能会被问到.
* implement memcpy? How to improve? how to determine if a system is
32bit or 64bit?
* how is static keyword used in Java?
* a list of intervals, no overlapping and sorted, write a function to
insert an interval into the list and still keep the list sorted and no
overlapping.... 阅读全帖
Basically the same solution with repeatable candidates. Recursion, time
complexity should be O(n!)?
import java.util.*;
public class Solution {
public ArrayList> combinationSum2(int[] num, int
target) {
ArrayList> result= new ArrayList
Integer>> ();
ArrayList item=new ArrayList ();
Arrays.sort(num);
if(num!=null || num.length>0)
combinations(num, target, result, item, 0);
public ArrayList> permuteUnique(int[] num) {
Arrays.sort(num);
ArrayList> output
= new ArrayList>();
ArrayList list = new ArrayList();
boolean col[] = new boolean[num.length];
permute(output,list,col,num,0);
return output;
}
public void permute(ArrayList> output,
ArrayList list,boolean col[]... 阅读全帖
这个能过OJ。
public class Solution {
public ArrayList> combinationSum(int[] candidates,
int target) {
// Start typing your Java solution below
// DO NOT write main() function
if(candidates == null || candidates.length == 0)
return new ArrayList>();
Arrays.sort(candidates);
ArrayList> ret = new ArrayList
>();
getCombination(candidates, 0, 0, target, ne... 阅读全帖
有没有java solution么?下面的代码是combination sum的,怎么在这个基础上改呢?
public class Solution {
public ArrayList> combinationSum(int[] candidates,
int target) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList> results = new ArrayList
Integer>>();
Arrays.sort(candidates);
addUp(candidates, 0, target, new ArrayList(), results);
return results;
}
private void addUp(i... 阅读全帖
Did you consider to skip duplicate element?
I pasted my solution as follows, hope it helps
public ArrayList> threeSum(int[] num) {
ArrayList> threeSum = new ArrayList
Integer>>();
if (num == null || num.length == 0)
return threeSum;
Arrays.sort(num);
int len = num.length;
int prev1 = Integer.MIN_VALUE;
int prev2 = Integer.MIN_VALUE;
int prev3 = Integer.MIN_VALUE;
for (... 阅读全帖
Subarray Sum
20%
Accepted
Given an integer array, find a subarray where the sum of numbers is zero.
Your code should return the index of the first number and the index of the
last number.
Example
Given [-3, 1, 2, -3, 4], return [0, 2] or [1, 3]. http://www.lintcode.com/en/problem/subarray-sum/
下面的解法总是在第16个test case Memory Limit Exceeded
public ArrayList subarraySum(int[] a) {
ArrayList res = new ArrayList();
//a map between sum and index
Has... 阅读全帖
相对于I来说只是一个很小的修改就可以了,
不过发现现在过不了OJ,总是提示TLE,
大家帮忙看看是什么问题?
谢谢!
public List> combinationSum2(int[] candidates, int target) {
List list = new ArrayList();
List> res = new ArrayList>();
Arrays.sort(candidates);
dfs(candidates, target, 0, list, res);
return res;
}
public void dfs(int[] candidates, int target, int start,
List list, List> res) {
给一个directed graph,要求打印出所有的环。
不知道我的Java code可行吗? 我用DFS traverse, 同时记住现在的path, 当侦测到
back edge时, 就打印出path中的cycle部分。
public void printCyclesInDirectedGraph(int n, int[] edges) {
List> graph = new ArrayList>(n);
for (int i = 0; i < n; i++)
graph.add(new LinkedList());
for (int [] e : edges)
graph.get(e[0]).add(e[1]);
int[] visited = new int[n];
for (int i = 0; i < n; i++) {
if (visited[i] == 0) {
List阅读全帖
Here is an idea and a proof sketch.
Solution: (c*a, c*b) for cubic numbers a and b and integer c >= 1. It is
easy to see those are solutions, but takes a proof to show that they are the
only solutions.
Observation: if (a,b) is a solution, then (k*a, k*b) is also a solution, for
integer k >= 1.
Claim: If (a, b) is a solution, then both a and b must be cubic numbers.
Now let's prove that claim. W.l.o.g. we may assume gcd(a,b) = 1, and we may
also assume that a is not a cubic number. Let p be a pri... 阅读全帖
打算用treeset实现一个最小堆。可是用了自己写的comparator以后,大数(如10000)
被认为是不同的数,因此不能去重复。请问为什么呢?
public class Test {
public static void main(String[] args) {
Set treeset = new TreeSet<>(new MyComparator());
Integer[] array = new Integer[args.length];
for (int i = 0 ; i < args.length ; i ++ ) {
array[i] = Integer.valueOf(args[i]);
treeset.add(array[i]);
}
for (Integer i : treeset) {
Syst... 阅读全帖
根据楼上的思想写了两个版本,不知道对不对
单调栈:
List findMinUnsortedSubArray(int[] nums) {
List res = new ArrayList<>(2);
if (nums == null || nums.length == 0) return res;
int n = nums.length;
Stack s = new Stack<>();
int max = Integer.MIN_VALUE;
s.push(-1);
for (int i=0; i
while (!s.isEmpty() && nums[i] < max && nums[i] < nums[s.peek()]
) {
s.pop();
}
if (nums[i]... 阅读全帖
636. Exclusive Time of Functions
Input:
n = 2
logs =
["0:start:0",
"1:start:2",
"1:end:5",
"0:end:6"]
Output:[3, 4]
这道题目,很有意思。
单线程求每个函数执行的总时间。
一共有
start end start end
start start end end
两种情况。
需要注意,开始时间是 第i秒的开始,结束时间是第i秒的最后。
class Solution {
public int[] exclusiveTime(int n, List logs) {
Stack stack = new Stack<>();
int[] res = new int[n];
String[] sa = logs.get(0).split(":");
int prev = Integer.parseInt(sa[2]);
stack.push(Integer.parse... 阅读全帖
1.
A binary gap within a positive integer N is any maximal sequence of
consecutive zeros that is surrounded by ones at both ends in the binary
representation of N.
For example, number 9 has binary representation 1001 and contains a binary
gap of length 2. The number 529 has binary representation 1000010001) and
contains two binary gaps: one of length 4 and one of length 3. The number 20
has binary representation 10100 and contains one binary gap of length 1.
The number 15 has binary representati... 阅读全帖
public static int solveDuplicateElement(Integer[] ar) {
int pos = 0, len = ar.length, bigO = 0;
while (pos < len) {
int slot = ar[pos];
if (slot == pos || slot == len) {
// being in place or invalidated
++pos;
} else {
int next = ar[slot];
if (next == slot) {... 阅读全帖
对于自己定义的数据(结构)的成员打印格式居然出问题。有兴趣的看一下为何主程序
最后两行打印结果不一样?gfortran and ifort give same results on linux.
=====save to test.f90, and then "ifort test.f90" and then "./a.out" to run=====
module numz
integer, parameter:: b8 = selected_real_kind(14)
integer,allocatable :: a_gene(:),many_genes(:,:)
end module
module galapagos
use numz
... 阅读全帖
对于自己定义的数据(结构)的成员打印格式居然出问题。有兴趣的看一下为何主程序
最后两行打印结果不一样?gfortran and ifort give same results on linux.
=====save to test.f90, and then "ifort test.f90" and then "./a.out" to run=====
module numz
integer, parameter:: b8 = selected_real_kind(14)
integer,allocatable :: a_gene(:),many_genes(:,:)
end module
module galapagos
use numz
... 阅读全帖
this article, Prof. William Dunham for information on the history of the
Twin Prime Conjecture, Prof. Liming Ge for biographic information about
Yitang Zhang, Prof. Shiu-Yuen Cheng for pointing out the paper of
Soundararajan cited in this article, Prof. Lo Yang for information about
Chengbiao Pan quoted below, and Prof. Yuan Wang for detailed information on
result... 阅读全帖
import java.util.ArrayList;
public ArrayList> uniqueSet(int[] a, int i) {
ArrayList retList = new ArrayList>();
if (i < 0) {
retList.add(new ArrayList);
return retList;
}
for (ArrayList list : uniqueSet(a, i - 1)) {
retList.add((ArrayList)(list.clone())); //ugly
list.add(new Integer(a[i]));
retList.add((ArrayList)(list.clone())); //ugly
}
return retList;
}