Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
O(n) Memory O(n) Time Solution
LTE? With an instantiated Iterator I can pass the OJ…
n+1 elements in range n, find the duplicate. take XOR between 1 to n, and the given array.
Here we use the property x^x=0,x^0=x
1
2
3
4
5
6
7
publicintsingleNumber(int[] A) {
int res = 0;
for(Integer i:A){
res ^= i;
}
return res;
}
Single Number II
Given an array of integers, every element appears three times except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Solution
count 1 in each bit position among all A numbers.
if a count can be divided by 3, then it does not contain single number
1
2
3
4
5
6
7
8
9
10
11
12
13
publicintsingleNumber(int[] A) {
int[] count = newint[32];
int res=0;
for(int i=0;i<32;i++){
for(int j=0;j<A.length;j++){
if((A[j]>>i & 1)==1){
count[i]+=1; //increment bit bin
}
}
res |= count[i]%3 << i; //recover single number
}
return res;
}
Decode Ways
A message containing letters from A-Z is being encoded to numbers using the following mapping:
1
2
3
4
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it. For example, Given encoded message “12”, it could be decoded as “AB” (1 2) or “L” (12). The number of ways decoding “12” is 2.
Recursive Solution
quite straight forward…? LTE..
when at i, we can decode i separately , or decode i,i+1 as a whole
checking conditions: 1X or <26, then we can return substr(1) + substr(2).
only when len==2 under this case, s.len would be 0, and return 1
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
1
2
3
4
5
6
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). Note: Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
Inplace DP Solution
start from second to end level, change each element to the smaller sum with lower level’s two adjacent elements