@skysbjdy
2016-12-08T22:57:48.000000Z
字数 11969
阅读 3928
Interview
Right Rotation
Example: waterbottle -> erbottlewat
bool rightRotation(string s1, string s2) {
if (s1.size() == 0 || s1.size() != s2.size()) {
return false;
}
s1 = s1 + s1;
return s1.find_first_of(s2) == string::npos ? false : true;
}
Gray Code 判断byte1和byte2是不是相邻的Gray Code
两个bytes 异或, 然后检查是不是只有一个1!!
bool gray(int byte1, int byte2) {
int temp = byte1 xor byte2;
int count = 0;
while(temp != 0) {
temp = temp & (temp - 1);
count++;
}
return count == 1 ? true : false;
}
Remove Vowel 去元音
string vowel(string s) {
string temp = "aeiouAEIOU";
string res = "";
for(int i = 0; i < s.size(); i++) {
if (temp.find_first_of(s[i]) != string::npos) continue;
res = res + s[i];
}
return res;
}
Valid Parenthesis 检验括号
一个str,里面只有 '('和‘)’,让你数valid pairs一共有多少,如果不是valid就返回-1. (判断是不是valid的parenthesis string,不是的话返回-1,是的话返回valid pair个数,即String.length() / 2 )
int parentheses(string s) {
stack<char> stc;
for(char c: s) {
if (c == '(') {
stc.push(c);
} else {
if (stc.empty()) return -1; //invalid
else stc.pop();
}
}
return stc.empty() ? s.size() / 2 : -1;
}
Longest Palindromic substring
string longestPalindrome(string s) {
int max = 0;
string res = "";
for (int i = 0; i < s.size(); i++) {
int left = i;
int right = i;
while(left - 1 >= 0 && right + 1 < s.size() && s[left - 1] == s[right + 1]) {
left--;
right++;
}
if (right - left + 1 > max) {
max = right - left + 1;
res = s.substr(left, right - left + 1);
}
if (i + 1 < s.size() && s[i] == s[i + 1]) {
left = i;
right = i + 1;
while(left - 1 >= 0 && right + 1 < s.size() && s[left - 1] == s[right + 1]) {
left--;
right++;
}
if (right - left + 1 > max) {
max = right - left + 1;
res = s.substr(left, right - left + 1);
}
}
}
return res;
}
Merge Two Sorted List
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode dummy(0);
ListNode* cur = &dummy;
while (l1 != NULL && l2 != NULL) {
if (l1->val < l2->val) {
cur->next = l1;
l1 = l1->next;
cur = cur->next;
} else {
cur->next = l2;
l2 = l2->next;
cur = cur->next;
}
}
cur->next = l1 != NULL ? l1 : l2;
return dummy.next;
}
Reverse Second Half of Linked List
[] -> []
[1] -> [1]
[1,2] -> [1,2]
[1,2,3] -> [1,2,3]
[1,2,3,4] -> [1,2,4,3]
[1,2,3,4,5] -> [1,2,3,5,4]
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
ListNode* slow = head;
ListNode* fast = head;
while(fast->next && fast->next->next) {
fast = fast->next->next;
slow = slow->next;
}
ListNode* cur = slow->next;
ListNode* pre = NULL;
while (cur) {
ListNode* nxt = cur->next;
cur->next = pre;
pre = cur;
cur = nxt;
}
slow->next = pre;
return head;
}
SubTree
LeetCode
bool isSubtree(TreeNode *T1, TreeNode *T2) {
// write your code here
if (T2 == NULL) return true;
if (T1 == NULL) return false;
return (isSame(T1, T2) || isSubtree(T1->left, T2) || isSubtree(T1->right, T2));
}
bool isSame(TreeNode* t1, TreeNode* t2) {
if (t1 == NULL && t2 == NULL) return true;
if (t1 == NULL || t2 == NULL) return false;
if (t1->val == t2->val) {
return isSame(t1->left, t2->left) && isSame(t1->right, t2->right);
} else {
return false;
}
}
Two Sum
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> map;
vector<int> res;
for(int i = 0; i < nums.size(); i++) {
if (map.find(target - nums[i]) != map.end()) {
res.push_back(map[target - nums[i]]);
res.push_back(i);
break;
}
else {
map[nums[i]] = i;
}
}
return res;
}
Find K Nearest Point
class point {
public:
int x;
int y;
point(int x_value, int y_value):x(x_value), y(y_value) {};
};
float distance(const point& a, const point& b = {0, 0}) {
int dx = a.x - b.x;
int dy = a.y - b.y;
return sqrt(dx * dx + dy * dy);
}
bool comp(const point& a, const point& b) {
point origin(0, 0);
return distance(a, {0, 0}) < distance(b, {0, 0});
}
struct mycomp {
bool operator()(const point& a, const point& b) {
point origin(0, 0);
return distance(a, origin) < distance(b, origin);
}
};
vector<point> KNearestPoint(vector<point> points, point origin, int k) {
priority_queue<point, std::vector<point>, decltype(&comp)> pq(&comp);
//priority_queue<point, std::vector<point>, mycomp> pq;
//priority_queue<point, std::vector<point>, bool (&)(point a, point b, point origin)> pq;
for (point p : points) {
pq.push(p);
if (pq.size() > k) {
pq.pop();
}
}
vector<point> res;
while (!pq.empty()) {
res.push_back(pq.top());
pq.pop();
}
return res;
}
Overlap Rectangle
//这个题目是左上角和右下角!!
bool doOverlap(Point l1, Point r1, Point l2, Point r2)
{
// If one rectangle is on left side of other
if (l1.x > r2.x || l2.x > r1.x)
return false;
// If one rectangle is above other
if (l1.y < r2.y || l2.y < r1.y)
return false;
return true;
}
(LeetCode计算面积)[https://leetcode.com/problems/rectangle-area/]
//!!注意这个题目给出的点是 左下角和右上角!!!! 而不是左上角和右下角
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int area1 = (C - A) * (D - B);
int area2 = (G - E) * (H - F);
int left = max(A, E);
int right = min (C, G);
int bottom = max(B, F);
int top = min(D, H);
int overlap = 0;
if (right > left && top > bottom)
overlap = (right - left) * (top - bottom);
return area1 + area2 - overlap;
}
Window Sum
vector<int> windowSum(vector<int> vect, int k) {
vector<int> res;
if (vect.size() == 0 || k <= 0) return res;
int sum = 0;
for (int i = 0; i < k; i++) {
sum += vect[i];
}
res.push_back(sum);
for (int i = 0; i < vect.size() - k; i++) { //注意这里的个数, 前面以及把第一项加进去了!! 所以不是size - k + 1
sum = sum - vect[i] + vect[i + k];
res.push_back(sum);
}
return res;
}
GCD Greatest Common Divisor
int solution(vector<int> array) {
if (array.size() == 0) return 0;
int res = array[0];
for (int i = 1; i < array.size(); i++) {
res = gcd(res, array[i]);
}
return res;
}
int gcd(int a, int b) {
a = a < 0 ? -a : a;
b = b < 0 ? -b : b;
if (a == 0 || b == 0) return a + b;
while (a != 0 && b != 0) {
if (a < b) swap(a, b); //make sure a is larger than b
int temp = a % b;
a = b;
b = temp;
}
return a + b;
}
LRU Cache count miss
int lruMiss(vector<int> nums, int capacity) {
list<int> ls;
int cnt = 0;
for (int num : nums) {
if(find(ls.begin(), ls.end(), num) != ls.end()) { //hit
ls.remove(num);
ls.push_back(num);
} else { //cache miss
cnt++;
if (ls.size() >= capacity) {
ls.pop_front();
}
ls.push_back(num);
}
}
return cnt;
}
Round Robin
class process {
public:
int arrTime;
int exeTime;
process(int arr, int exe) {
arrTime = arr;
exeTime = exe;
}
};
float roundRobin(vector<int> Atime, vector<int> Etime, int q) {
if (Atime.size() == 0 || Etime.size() == 0 || Atime.size() != Etime.size()) return 0.0;
queue<process> jobs;
int index = 0;
int curTime = 0;
int waitTime = 0;
while (!jobs.empty() || index < Atime.size()) {
if (!jobs.empty()) {
process curJob = jobs.front();
jobs.pop();
waitTime += curTime - curJob.arrTime;
curTime += curJob.exeTime < q ? curJob.exeTime : q;
//加入所有到达的job
for (; index < Atime.size() && Atime[index] <= curTime; index++) {
jobs.push(process(Atime[index], Etime[index]));
}
//注意顺序!! 最后把没有执行完的当前任务放在队列最后面!!!
if (curJob.exeTime > q) {
jobs.push(process(curTime, curJob.exeTime - q));
}
} else {
//只加入第一个 没有for循环
jobs.push(process(Atime[index], Etime[index]));
curTime = Atime[index]; //设置时间
index++;
}
}
return (float)waitTime / Atime.size();
}
Rotation Matrix
vector<vector<int>> rotation(vector<vector<int>> matrix, int flag) {
int m = matrix.size();
if (m == 0) return matrix;
int n = matrix[0].size();
vector<vector<int>> res(n, vector<int>(m, 1));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
res[j][i] = matrix[i][j];
}
}
if (flag == 0) { // turn right -> left right flip
for (int i = 0; i < n; i++) {
for (int j = 0; j < m / 2; j++) {
swap(res[i][j], res[i][m - 1 - j]); //注意减一
}
}
} else { //turn left -> upside down flip
for (int i = 0; i < m; i++) {
for (int j = 0; j < n / 2; j++) {
swap(res[j][i], res[n - 1 - j][i]); //注意减一, i j的位置是颠倒的
}
}
}
return res;
}
Insert into cycle linked list
ListNode Solution(ListNode head, int val) {
if (head == null) {
ListNode rvalue = new ListNode(val);
rvalue.next = rvalue; //自己跟自己形成环
eturn rvalue;
}
ListNode cur = head;
do {
//一般情况: 直接找到正确的位子
if (val <= cur.next.val && val >= cur.val) break;
//特殊情况: 正好在首尾连接处
if (cur.val > cur.next.val && (val < cur.next.val || val > cur.val)) break;
cur = cur.next;
} while (cur != head);
ListNode newNode = new ListNode(val);
newNode.next = cur.next;
cur.next = newNode;
return newNode;
}
Loop in linked list
ListNode *detectCycle(ListNode *head) {
if (head == NULL || head->next == NULL) return NULL;
ListNode* slow = head->next;
ListNode* fast = head->next->next;
while (slow != fast && fast) {
slow = slow->next;
fast = fast->next;
if (fast) fast = fast->next;
}
if (fast == NULL) return NULL;
slow = head;
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
return fast;
}
Round Robin Shortest First
class Process {
public:
int arrTime;
int exeTime;
Process(int aTime, int eTime) {
arrTime = aTime;
exeTime = eTime;
}
};
bool comp(Process a, Process b) {
if (a.exeTime == b.exeTime) return a.arrTime > b.arrTime;
return a.exeTime > b.exeTime;
}
float roundRobin(vector<int> aTime, vector<int> eTime) {
if (aTime.size() == 0 || eTime.size() == 0 || aTime.size() != eTime.size()) return 0.0;
//pq comp的写法 取函数地址, 而且声明的时候要传参数!!!
priority_queue<Process, vector<Process>, decltype(&comp)> jobs(&comp);
int index = 0;
int curTime = aTime[0];
int waitTime = 0;
while (index < aTime.size() || (!jobs.empty())) {
if (!jobs.empty()) {
Process curJob = jobs.top();
jobs.pop();
waitTime += curTime - curJob.arrTime;
curTime += curJob.exeTime;
} else {
for (; index < aTime.size() && aTime[index] <= curTime; index++) {
jobs.push(Process(aTime[index], eTime[index]));
}
}
}
return (float) waitTime / aTime.size();
}
Binary Search Tree Minimum Sum From Root to Leaf
int minSum(TreeNode* root) {
if (root == NULL) return 0;
if (root->left == NULL && root->right == NULL) return root->val;
if (root->left != NULL && root->right == NULL) {
return root->val + minSum(root->left);
} else if (root->left == NULL && root->right != NULL) {
return root->val + minSum(root->right);
} else {
return root->val + min(minSum(root->left), minSum(root->right));
}
}
Day change(cell growth)
vector<int> cellGrowth(vector<int> cells, int n) {
int len = cells.size();
cells.insert(cells.begin(), 0);
cells.push_back(0);
for (int i = 0; i < n; i++) {
int pre = 0;
for (int j = 1; j <= len; j++) {
int temp = cells[j];
cells[j] = pre == cells[j + 1] ? 0 : 1;
pre = temp;
}
}
cells.erase(cells.begin());
cells.pop_back();
for (int cell : cells) {
cout << cell << endl;
}
return cells;
}
Maze
bool mazePath(vector<vector<int>> maze) {
int m = maze.size();
if (m == 0) return true;
int n = maze[0].size();
if (maze[0][0] == 0) return false; //0 means block
if (maze[0][0] == 9) return true; //corner case
vector<int> dx = {0, 1, 0, -1};
vector<int> dy = {1, 0, -1, 0};
queue<pair<int, int>> q;
q.push({0, 0});
while (!q.empty()) {
int x = q.front().first;
int y = q.front().second;
q.pop();
maze[x][y] = -1;
for (int index = 0; index < 4; index++) {
int i = x + dx[index];
int j = y + dy[index];
if (i >= 0 && i < m && j >= 0 && j < n) {
if (maze[i][j] == 9) return true; //check if it is the end
if (maze[i][j] == 1) q.push({i, j});
}
}
}
return false;
}
Min Window
LeetCode
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
deque<int> q;
vector<int> res;
for(int i = 0; i < nums.size(); i++) {
while (!q.empty() && nums[q.back()] < nums[i]) q.pop_back(); //q永远保持降序
q.push_back(i);
if (i - q.front() + 1 > k) q.pop_front();//确保他还在范围内!!!
if(i >= k - 1) res.push_back(nums[q.front()]);
}
return res;
}
Four Integer
int comp(const void* a, const void* b) {
return (*(int*)a) - (*(int*)b);
}
vector<int> fourInt(int a, int b, int c, int d) {
vector<int> res = {a, b, c, d};
qsort(&res[0], res.size(), sizeof(int), comp);
swap(res[0], res[1]);
swap(res[2], res[3]);
swap(res[0], res[3]);
return res;
}
Arithmetic Sequence
给一个数组,返回可能的等差数列个数
int numberOfArithmeticSlices(vector<int>& A) {
if (A.size() < 3) return 0;
int diff = 0;
int start = 0;
int cnt = 0;
int res = 0;
for (int i = 1; i < A.size(); i++) {
int curDiff = A[i] - A[i - 1];
if (curDiff == diff) {
cnt += (i - start - 1) > 0 ? i - start - 1 : 0; //注意 为什么是加上这个多个??
} else {
start = i - 1;
diff = A[i] - A[i - 1];
res += cnt;
cnt = 0;
}
}
res += cnt;
return res;
}
Tree Amplitude
int TreeAmplitude(TreeNode* root) {
if (root == NULL) return 0;
return helper(root, root->val, root->val);
}
int helper(TreeNode* root, int& max, int& min) {
if (root == NULL) return max - min;
if (root->val < min) min = root->val;
if (root->val > max) max = root->val;
return max(helper(root->left, max, min), helper(root->right, max, min));
}
Maximum Minimum Path
int mmPath(vector<vector<int>>& matrix) {
if (matrix.size() == 0) return 0;
int max = INT_MIN;
int min = INT_MAX;
helper(matrix, max, min, 0, 0);
return max;
}
void helper(vector<vector<int>>& matrix, int& max, int min, int i, int j) {
if (i >= matrix.size() || j >= matrix[0].size()) {
return;
}
if (i == matrix.size() - 1 && j == matrix[0].size() - 1) {
min = min < matrix[i][j] ? min : matrix[i][j];
max = max > min ? max : min;
return;
}
min = min < matrix[i][j] ? min : matrix[i][j];
helper(matrix, max, min, i + 1, j);
helper(matrix, max, min, i, j + 1);
return;
}
Search in 2D matrix
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size();
if (m == 0) return false;
int n = matrix[0].size();
int i = 0;
int j = m * n - 1;
while (i <= j) { //考虑最后一个步
int mid = i + (j - i) / 2;
if (matrix[mid / n][ mid % n] == target) return true;
if (matrix[mid / n][mid % n] < target) {
i = mid + 1;
} else {
j = mid - 1;
}
}
return false;
}
Search in 2D matrix II
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size();
if (m == 0) return false;
int n = matrix[0].size();
int i = 0;
int j = n - 1; //从右上角开始
while (i < m && j >= 0) {
if (matrix[i][j] == target) return true;
if (matrix[i][j] < target) {
i++;
} else {
j--;
}
}
return false;
}
Close Two Sum
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
double capacity = 35;
double[] weights = {10,24,30,9,19,23,7};
double maxWei = 0;
double maxSmall = 0;
double maxLarge = 0;
Arrays.sort(weights);
int i = 0;
int j = weights.length-1;
while (i < j) {
if ((weights[i] + weights[j]) < capacity) {
if (weights[i] + weights[j] > maxWei) {
maxWei = weights[i] + weights[j];
maxSmall = weights[i];
maxLarge = weights[j];
}
i += 1;
} else if (weights[i] + weights[j] == capacity) {
maxSmall = weights[i];
maxLarge = weights[j];
maxWei = capacity;
break;
} else {
j -= 1;
}
}
System.out.println("The maximum weights is" + maxWei + ", the index are" + maxSmall + "and" + maxLarge);
}
}