Fork me on GitHub
hazelnutsgz

Why don't you come to your senses?


  • Home

  • About

  • Tags

  • Archives

Closest Binary Search Tree Value II

Posted on 2018-10-16

Description

https://leetcode.com/problems/closest-binary-search-tree-value-ii/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct cmp {
bool operator () (pair<float, int>& A, pair<float, int>& B) {
return A.first < B.first;
}
};

class Solution {
public:
vector<int> closestKValues(TreeNode* root, double target, int k) {

priority_queue<pair<float, int>, vector<pair<float, int>>, cmp> pq;
inOrderTraverse(root, target, k, pq);
vector<int> ret;
while (!pq.empty()) {
ret.push_back(pq.top().second);
pq.pop();
}
return ret;
}

void inOrderTraverse(TreeNode* root, double target, int k,
priority_queue<pair<float, int>, vector<pair<float, int>>, cmp>& pq) {
if (root == NULL) return;
inOrderTraverse(root->left, target, k, pq);
auto pa = make_pair(abs(root->val - target), root->val);
if (pq.size() >= k) {
if (pa.first < pq.top().first) {
pq.pop();
pq.push(pa);
}
}else {
pq.push(pa);
}
inOrderTraverse(root->right, target, k, pq);
}
};

Design Hit Counter

Posted on 2018-10-16

Description

Design a hit counter which counts the number of hits received in the past 5 minutes.

Each function accepts a timestamp parameter (in seconds granularity) and you may assume that calls are being made to the system in chronological order (ie, the timestamp is monotonically increasing). You may assume that the earliest timestamp starts at 1.

It is possible that several hits arrive roughly at the same time.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
HitCounter counter = new HitCounter();

// hit at timestamp 1.
counter.hit(1);

// hit at timestamp 2.
counter.hit(2);

// hit at timestamp 3.
counter.hit(3);

// get hits at timestamp 4, should return 3.
counter.getHits(4);

// hit at timestamp 300.
counter.hit(300);

// get hits at timestamp 300, should return 4.
counter.getHits(300);

// get hits at timestamp 301, should return 3.
counter.getHits(301);

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#define RANGE 300
class HitCounter {
public:
map<int, int> times;
int count;
int pre;
/** Initialize your data structure here. */
HitCounter() {
count = 0;
pre = -1;
}

/** Record a hit.
@param timestamp - The current timestamp (in seconds granularity). */
void hit(int timestamp) {
if (pre != timestamp){
times[timestamp] = count;
pre = timestamp;
}
++count;
}

/** Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity). */
int getHits(int timestamp) {
int start = timestamp - RANGE + 1;
auto iter = times.lower_bound(start);
if (iter == times.end() ) return 0;
return count - iter->second;
}
};

/**
* Your HitCounter object will be instantiated and called as such:
* HitCounter obj = new HitCounter();
* obj.hit(timestamp);
* int param_2 = obj.getHits(timestamp);
*/

Robot Room Cleaner

Posted on 2018-10-16

Description

https://leetcode.com/problems/robot-room-cleaner/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* // This is the robot's control interface.
* // You should not implement it, or speculate about its implementation
* class Robot {
* public:
* // Returns true if the cell in front is open and robot moves into the cell.
* // Returns false if the cell in front is blocked and robot stays in the current cell.
* bool move();
*
* // Robot will stay in the same cell after calling turnLeft/turnRight.
* // Each turn will be 90 degrees.
* void turnLeft();
* void turnRight();
*
* // Clean the current cell.
* void clean();
* };
*/
class Solution {
public:
void cleanRoom(Robot& robot) {
int x = 0;
int y = 0;
unordered_map<int, unordered_map<int, bool>> visited;
int direction = 0;
cleanHelper(robot, visited, x, y, direction);
return;
}

void cleanHelper(Robot& robot, unordered_map<int, unordered_map<int, bool>>& visited, int x, int y, int direction) {
if (visited[x][y] == true) return;
vector<vector<int>> directions = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
visited[x][y] = true;
robot.clean();
for (int i = 0; i < 4; ++i) {
if (robot.move()) {
cleanHelper(robot, visited, x + directions[direction][0], y + directions[direction][1], direction);
robot.turnLeft();
robot.turnLeft();
robot.move();
robot.turnLeft();
robot.turnLeft();
}
robot.turnLeft();
direction = (direction + 1) % 4;
}
return;
}

};

Employee Free Time

Posted on 2018-10-16

Description

https://leetcode.com/problems/employee-free-time/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {

public:
bool static compare(Interval& a, Interval& b) {
return a.start < b.start;
}
vector<Interval> employeeFreeTime(vector<vector<Interval>>& schedule) {
vector<Interval> whole;
for (auto& item : schedule) {
for (auto& item2 : item) {
whole.push_back(item2);
}
}
sort(whole.begin(), whole.end(), compare);

int pre = -1;
vector<Interval> merged;
for (int index = 0; index < whole.size(); ++index) {
if (whole[index].start > pre) {
merged.push_back(whole[index]);
}else {
merged[merged.size() - 1].end =
max(whole[index].end, merged[merged.size() - 1].end);
}
pre = merged[merged.size() - 1].end;
}
vector<Interval> ret;
for (int index = 0; index < merged.size() - 1; ++index) {
ret.push_back(Interval(merged[index].end, merged[index + 1].start));
}
return ret;
}
};

Binary Tree Vertical Order Traversal

Posted on 2018-10-15

Description

Given a binary tree, return the vertical order traversal of its nodes’ values. (ie, from top to bottom, column by column).

If two nodes are in the same row and column, the order should be from left to right.

Examples 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Input: [3,9,20,null,null,15,7]

3
/\
/ \
9 20
/\
/ \
15 7

Output:

[
[9],
[3,15],
[20],
[7]
]

Examples 2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Input: [3,9,8,4,0,1,7]

3
/\
/ \
9 8
/\ /\
/ \/ \
4 01 7

Output:

[
[4],
[9],
[3,0,1],
[8],
[7]
]

Examples 3:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Input: [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5)

3
/\
/ \
9 8
/\ /\
/ \/ \
4 01 7
/\
/ \
5 2

Output:

[
[4],
[9,5],
[3,0,1],
[8,2],
[7]
]

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> verticalOrder(TreeNode* root) {
vector<vector<int>> ret;
if (root == NULL) return ret;
map<int, map<int, vector<int>>> matrix;
traverseNode(root, matrix, 0, 0);
for (auto& item1 : matrix) {
vector<int> vec;
cout << item1.first << endl;
for (auto& item2 : item1.second) {
for (auto& item3 : item2.second) {
vec.push_back(item3);
}
}
ret.push_back(vec);
}

return ret;
}

void traverseNode(TreeNode* root, map<int, map<int, vector<int>> >& matrix, int depth, int width) {
if (root == NULL) return;
traverseNode(root->left, matrix, depth + 1, width - 1);
matrix[width][depth].push_back(root->val);
traverseNode(root->right, matrix, depth + 1, width + 1);
return;
}
};

Untitled

Posted on 2018-10-15

Description

Given a nested list of integers, return the sum of all integers in the list weighted by their depth.

Each element is either an integer, or a list – whose elements may also be integers or other lists.

Different from the previous question where weight is increasing from root to leaf, now the weight is defined from bottom up. i.e., the leaf level integers have weight 1, and the root level integers have the largest weight.

Example 1:

1
2
3
Input: [[1,1],2,[1,1]]
Output: 8
Explanation: Four 1's at depth 1, one 2 at depth 2.

Example 2:

1
2
3
Input: [1,[4,[6]]]
Output: 17
Explanation: One 1 at depth 3, one 4 at depth 2, and one 6 at depth 1; 1*3 + 4*2 + 6*1 = 17.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* public:
* // Constructor initializes an empty nested list.
* NestedInteger();
*
* // Constructor initializes a single integer.
* NestedInteger(int value);
*
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* bool isInteger() const;
*
* // Return the single integer that this NestedInteger holds, if it holds a single integer
* // The result is undefined if this NestedInteger holds a nested list
* int getInteger() const;
*
* // Set this NestedInteger to hold a single integer.
* void setInteger(int value);
*
* // Set this NestedInteger to hold a nested list and adds a nested integer to it.
* void add(const NestedInteger &ni);
*
* // Return the nested list that this NestedInteger holds, if it holds a nested list
* // The result is undefined if this NestedInteger holds a single integer
* const vector<NestedInteger> &getList() const;
* };
*/
class Solution {
public:
int depthSumInverse(vector<NestedInteger>& nestedList) {
int size = nestedList.size();
vector<pair<int, int>> slot;
if (size == 0) return 0;
int maxDepth = -1;
for (int i = 0; i < size; ++i) {
findDepth(slot, nestedList[i], 1, maxDepth);
}
int ret = 0;
for (int i = 0 ;i < slot.size(); ++i) {
ret += (maxDepth + 1 - slot[i].first) * slot[i].second;
}
return ret;
}

void findDepth(vector<pair<int, int>>& slot, NestedInteger& nested, int currentDepth, int& maxDepth) {
maxDepth = max(currentDepth, maxDepth);
if (nested.isInteger()) {
slot.push_back(make_pair(currentDepth, nested.getInteger()) );
return;
}
auto& lis = nested.getList();
for (int i = 0; i < lis.size(); ++i) {
findDepth(slot, lis[i], currentDepth + 1, maxDepth);
}
return;
}
};

Inorder Successor in BST

Posted on 2018-10-15

Description

https://leetcode.com/problems/inorder-successor-in-bst/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
if (root == NULL) return NULL;
unordered_map<TreeNode*, int> mapping;
vector<TreeNode*> vec;
int index = 0;
traverseNode(mapping, vec, root);
int targetIndex = mapping[p];
if (targetIndex >= vec.size() - 1) return NULL;
return vec[targetIndex + 1];
}

void traverseNode(unordered_map<TreeNode*, int>& mapping, vector<TreeNode*>& vec, TreeNode* root) {
if (root == NULL) return;
traverseNode(mapping, vec, root->left);
mapping[root] = vec.size();
vec.push_back(root);
traverseNode(mapping, vec, root->right);
return;
}
};

Quick Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
if (root == NULL) return NULL;
TreeNode* traverse = root;
TreeNode* ret = NULL;

while (traverse) {
if (p->val < traverse->val) {
ret = traverse;
traverse = traverse->left;
}else {
traverse = traverse->right;
}

}

return ret;
}

};

Design Snake Game

Posted on 2018-10-13

Description

https://leetcode.com/problems/design-snake-game/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class SnakeGame {
private:
// vector<vector<int>> grid;
int headX;
int headY;
int count;
int height;
int width;
queue<pair<int, int>> que;
unordered_map<string, pair<int, int>> directions;
map<pair<int, int>, bool> occupied;
vector<pair<int, int>> foods;
public:
/** Initialize your data structure here.
@param width - screen width
@param height - screen height
@param food - A list of food positions
E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. */
SnakeGame(int width, int height, vector<pair<int, int>> food) {
// vector<vector<int>> newGrid(height, vector<int>(width));
// grid = newGrid;
directions["R"] = make_pair(0, 1);
directions["L"] = make_pair(0, -1);
directions["U"] = make_pair(-1, 0);
directions["D"] = make_pair(1, 0);
this->height = height;
this->width = width;
headX = 0;
headY = 0;

que.push(make_pair(headX, headY));
occupied[make_pair(headX, headY)] = true;
count = 0;
foods = food;
}

/** Moves the snake.
@param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down
@return The game's score after the move. Return -1 if game over.
Game over when snake crosses the screen boundary or bites its body. */
int move(string direction) {
int newX = headX + directions[direction].first;
int newY = headY + directions[direction].second;

//Hit the wall
if (newX < 0 || newX >= height || newY < 0 || newY >= width) return -1;


//Pay attention to the order of push and pop, we should try pop(shorten) the snake befroe we push pos into it.
if (count < foods.size() && newX == foods[count].first && newY == foods[count].second) count += 1;
else {
pair<int, int> erase = que.front();
que.pop();
occupied.erase(erase);
}

if (occupied.count(make_pair(newX, newY)) != 0) return -1; //Hit itself
occupied[make_pair(newX, newY)] = true;
que.push(make_pair(newX, newY));

headX = newX;
headY = newY;

return count;
}
};

Length of Longest Fibonacci Subsequence

Posted on 2018-10-13

Description

https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int lenLongestFibSubseq(vector<int>& A) {
int size = A.size();
unordered_map<int, int> counter;
for (int i = 0; i < size; ++i) counter[A[i]] = i;

vector<vector<int>> dp(size, vector<int>(size, 2));

int ret = 0;
for (int i = 1; i < size - 1; ++i) {
for (int j = i + 1; j < size; ++j){
int target = A[j] - A[i];
if (target >= A[i]) break;
auto iter = counter.find(target);
if (iter == counter.end()) continue;
dp[i][j] = dp[iter->second][i] + 1;
ret = max(ret, dp[i][j]);
}
}
return ret;
}
};

Design Tic-Tac-Toe

Posted on 2018-10-12

Description

Design a Tic-tac-toe game that is played between two players on a n x n grid.

You may assume the following rules:

  1. A move is guaranteed to be valid and is placed on an empty block.
  2. Once a winning condition is reached, no more moves is allowed.
  3. A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal row wins the game.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
Given n = 3, assume that player 1 is "X" and player 2 is "O" in the board.

TicTacToe toe = new TicTacToe(3);

toe.move(0, 0, 1); -> Returns 0 (no one wins)
|X| | |
| | | | // Player 1 makes a move at (0, 0).
| | | |

toe.move(0, 2, 2); -> Returns 0 (no one wins)
|X| |O|
| | | | // Player 2 makes a move at (0, 2).
| | | |

toe.move(2, 2, 1); -> Returns 0 (no one wins)
|X| |O|
| | | | // Player 1 makes a move at (2, 2).
| | |X|

toe.move(1, 1, 2); -> Returns 0 (no one wins)
|X| |O|
| |O| | // Player 2 makes a move at (1, 1).
| | |X|

toe.move(2, 0, 1); -> Returns 0 (no one wins)
|X| |O|
| |O| | // Player 1 makes a move at (2, 0).
|X| |X|

toe.move(1, 0, 2); -> Returns 0 (no one wins)
|X| |O|
|O|O| | // Player 2 makes a move at (1, 0).
|X| |X|

toe.move(2, 1, 1); -> Returns 1 (player 1 wins)
|X| |O|
|O|O| | // Player 1 makes a move at (2, 1).
|X|X|X|

Follow up:
Could you do better than O(n2) per move() operation?

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
class TicTacToe {
private:
vector<vector<int>> grid;
vector<int> rowSum;
vector<int> rowProduct;
vector<int> colSum;
vector<int> colProduct;
vector<int> diagonalSum;
vector<int> diagonalProduct;
int size;
vector<int> playerProduct;
public:
/** Initialize your data structure here. */
TicTacToe(int n) {
vector<vector<int>> newGrid(n, vector<int>(n, 0));
grid = newGrid;

//Target
playerProduct.push_back(1);
playerProduct.push_back(1 << n);

//Sum
rowSum.resize(n);
colSum.resize(n);
diagonalSum.resize(2);

//Product
for (int i = 0; i < n; ++i) {
rowProduct.push_back(1);
colProduct.push_back(1);
}
diagonalProduct.push_back(1);
diagonalProduct.push_back(1);
size = n;
}

/** Player {player} makes a move at ({row}, {col}).
@param row The row of the board.
@param col The column of the board.
@param player The player, can be either 1 or 2.
@return The current winning condition, can be either:
0: No one wins.
1: Player 1 wins.
2: Player 2 wins. */
int move(int row, int col, int player) {
grid[row][col] = player;


rowSum[row] += player;
rowProduct[row] *= player;

colSum[col] += player;
colProduct[col] *= player;

if (int pos = diagonal(row, col)) {
if (pos == 3) {
diagonalSum[0] += player;
diagonalSum[1] += player;
diagonalProduct[0] *= player;
diagonalProduct[1] *= player;
}else {
diagonalSum[pos - 1] += player;
diagonalProduct[pos - 1] *= player;
}


if ( (diagonalSum[0] == size * player
&& diagonalProduct[0] == playerProduct[player - 1])
|| (diagonalSum[1] == size * player
&& diagonalProduct[1] == playerProduct[player - 1])
)
return player;
}

if ( (rowSum[row] == size * player && rowProduct[row] == playerProduct[player - 1])
|| (colSum[col] == size * player && colProduct[col] == playerProduct[player - 1]) )
return player;

return 0;
}

int diagonal(int row, int col) {
if (size % 2 && row == size / 2 && col == size / 2) return 3;
if (row == col) return 2;
if (row + col == size - 1) return 1;
return 0;
}
};

/**
* Your TicTacToe object will be instantiated and called as such:
* TicTacToe obj = new TicTacToe(n);
* int param_1 = obj.move(row,col,player);
*/
1…678…21

hazelnutsgz

A normal coder

210 posts
9 tags
Github LinkedIn
© 2019 hazelnutsgz
本站访客数:
|
Theme — NexT.Muse v5.1.4
总访问量次 | 总访客人 |