zzm99


  • Home

  • Tags

  • Categories

  • Archives

  • Search

Weekly Contest 154

Posted on 2019-09-17 | In leetcode , Weekly-Contest |
Words count in article: 1.5k | Reading time ≈ 8

Maximum Number of Balloons

Given a string text, you want to use the characters of text to form as many instances of the word “balloon” as possible.

You can use each character in text at most once. Return the maximum number of instances that can be formed.

1
2
3
4
5
6
7
8
9
10
11
12
13
Example 1:

Input: text = "nlaebolko"
Output: 1
Example 2:


Input: text = "loonbalxballpoon"
Output: 2
Example 3:

Input: text = "leetcode"
Output: 0

Constraints:

  • 1 <= text.length <= 10^4
  • text consists of lower case English letters only.
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
class Solution {
public:
int maxNumberOfBalloons(string text) {
int rem[5];
for(int i=0; i<5; i++)
rem[i] = 0;
for(int i=0; i<text.size(); i++)
{
if(text[i] == 'b')
rem[0]++;
else if(text[i] == 'a')
rem[1]++;
else if(text[i] == 'l')
rem[2]++;
else if(text[i] == 'o')
rem[3]++;
else if(text[i] == 'n')
rem[4]++;
}
rem[2] /= 2;
rem[3] /= 2;
int ret = rem[0];
for(int i=1; i<5; i++)
{
if(rem[i] < ret)
ret = rem[i];
}
return ret;
}
};

K-Concatenation Maximum Sum

Given an integer array arr and an integer k, modify the array by repeating it k times.

For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2].

Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0.

As the answer can be very large, return the answer modulo 10^9 + 7.

1
2
3
4
5
6
7
8
9
10
11
12
Example 1:

Input: arr = [1,2], k = 3
Output: 9
Example 2:

Input: arr = [1,-2,1], k = 5
Output: 2
Example 3:

Input: arr = [-1,-2], k = 7
Output: 0

Constraints:

  • 1 <= arr.length <= 10^5
  • 1 <= k <= 10^5
  • -10^4 <= arr[i] <= 10^4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1. all positive : [1,2,3], k = 3, array_sum = 6
return array_sum*3
2. all negative : [-1,-2], k = 2, array_sum = -3
return 0
3. hybrid, with array_sum <= 0, [2,1,-3], k = 4, array_sum = 0
[ 2, 1, -3, 2, 1, -3, 2, 1, -3, 2, 1, -3]
max sum 2 3 0 2 3 0 2 3 0 2 3 0
return max_subarray_sum between [2,1,-3,2,1,-3] which is twice of original array
so, return max_subarray_sum = 3
4. hybrid, with array_sum > 0, [2,-6,5], k =4, array_sum = 1
[ 2, -6, 5, 2, -6, 5, 2, -6, 5, 2, -6, 5]
max sum 2 0 5 7 1 6 8 2 7 9 3 8
a. you can notice max subarray sum is getting bigger as k grows up.
b. with first 2 array, we can get max subarray sum is 8.
c. after that, with each new array, max_subarray_sum will increase by 1, which is array_sum
==>return (max_subarray_sum when k=2) + array_sum*(k-2)
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
class Solution {
public:
int kConcatenationMaxSum(vector<int>& arr, int k) {
// k = 1
if(k == 1)
{
long long maxsubarraysum = 0, tmpsum = 0;

for(int i=0; i<arr.size(); i++)
{
tmpsum = max(tmpsum + (long long)arr[i], (long long)arr[i]);
maxsubarraysum = max(maxsubarraysum, tmpsum);
}

return maxsubarraysum % 1000000007;
}
// k > 1
// get array sum
long long arraysum = accumulate(arr.begin(), arr.end(), 0);

// generate two times arr
vector<int> arrcascade(arr.begin(), arr.end());
arrcascade.insert(arrcascade.begin(), arr.begin(), arr.end());
long long maxsubarraysum = 0, tmpsum = 0;

//calculate maxsubarraysum(k=2)

for(int i=0; i<arrcascade.size(); i++)
{
tmpsum = max(tmpsum + (long long)arrcascade[i], (long long)arrcascade[i]);
maxsubarraysum = max(maxsubarraysum, tmpsum);
}

return (maxsubarraysum+(arraysum > 0 ? arraysum*(k-2):0)) % 1000000007;
}
};

Reverse Substrings Between Each Pair of Parentheses

Given a string s that consists of lower case English letters and brackets.

Reverse the strings in each pair of matching parentheses, starting from the innermost one.

Your result should not contain any bracket.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Example 1:

Input: s = "(abcd)"
Output: "dcba"
Example 2:

Input: s = "(u(love)i)"
Output: "iloveu"
Example 3:

Input: s = "(ed(et(oc))el)"
Output: "leetcode"
Example 4:

Input: s = "a(bcdefghijkl(mno)p)q"
Output: "apmnolkjihgfedcbq"

Constraints:

  • 0 <= s.length <= 2000
  • s only contains lower case English characters and parentheses.
  • It’s guaranteed that all parentheses are balanced.

给一个有括号的字符串,一个匹配的括号代表括号里的内容需要反转。

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
class Solution {
public:
string reverseParentheses(string s) {
string tmp;
stack<string> sta;
for(auto c: s)
{
if(c == '(')
{
sta.push(tmp);
tmp.clear();
}
else if(c == ')')
{
string pre;
if(!sta.empty())
{
pre = sta.top();
sta.pop();
}
reverse(tmp.begin(), tmp.end());
pre += tmp;
tmp = pre;
}
else
{
tmp.push_back(c);
}
}
return tmp;
}
};

Critical Connections in a Network

There are n servers numbered from 0 to n-1 connected by undirected server-to-server connections forming a network where connections[i] = [a, b] represents a connection between servers a and b. Any server can reach any other server directly or indirectly through the network.

A critical connection is a connection that, if removed, will make some server unable to reach some other server.

Return all critical connections in the network in any order.

1
2
3
4
Example 1:
Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]
Output: [[1,3]]
Explanation: [[3,1]] is also accepted.

Constraints:

  • 1 <= n <= 10^5
  • n-1 <= connections.length <= 10^5
  • connections[i][0] != connections[i][1]
  • There are no repeated connections.

给一个无向连通图,求所有割边(桥)。

割边定义:删除这个边,连通图就不再联通,即被划分为两个独立部分。

Tarjan 方法

对于一个连通图,递归可以访问到所有顶点和边。

1
2
3
4
5
6
7
8
9
 ------------
| |
1 --- 2 ---- 3
|
|
|
4 --- 5
| |
---- 6

而对于割边,例如2-4,递归的时候,2-4递归的所有顶点都大于2。

而对于非割边,比如5-6,递归的时候,6可以找到更小的4。

总结一下就是,这个边递归找的最小编号都比自己大,那这个边就是割边,否则不是割边。

所以我们需要做的就是递归寻找每个顶点能够到达的最小编号,然后比大小即可。

tarjan

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
class Solution {
public:
vector<vector<int>> res;
int index = 0; // 访问序号
vector<int> dfn; // 当前访问的序号
vector<int> low; // 当前节点&其子树 最早访问的序号

vector<vector<int>> graph;
void tarjan(int cur, int last)
{
low[cur] = dfn[cur] = index++; // 分配一个序号
for (const auto& next : graph[cur])
{
if(next == last) continue; // 避免重复访问
if (dfn[next] == -1)
{
tarjan(next, cur); // 没有访问过,继续搜索
low[cur] = min(low[cur], low[next]); // 更新最早序号
if(low[next] > dfn[cur]) // 新的节点的low已经大于当前节点的序号,说明已经不在同一个强联通分量里了
{
res.push_back({cur, next}); // 加入到结果中
}
}
else
{
low[cur] = min(low[cur], dfn[next]);// 访问过了,直接更新
//low[cur] = min(low[cur], low[next]); -> I think this is right !
}
}
}

vector<vector<int>> criticalConnections(int n, vector<vector<int>>& connections) {
dfn.resize(n, -1);
low.resize(n, -1);
graph.resize(n);
for (int i = 0; i < connections.size(); i++)
{
vector<int>& c = connections[i];
int v1 = c[0];
int v2 = c[1];
graph[v1].push_back(v2);
graph[v2].push_back(v1);
}
tarjan(0, -1); // 处在同一个强联通分量中节点, 最终会得到相同的low值
// for(int i = 0;i < n;i++) cout << low[i] << " " << dfn[i] << endl;
return res;
}
};

leetcode-437-Path Sum III

Posted on 2019-09-16 | In leetcode , top-100-liked-questions |
Words count in article: 190 | Reading time ≈ 1

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1

Return 3. The paths that sum to 8 are:

1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//dfs
public class Solution {
public int pathSum(TreeNode root, int sum) {
if(root == null)
return 0;
return findPath(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
}

public int findPath(TreeNode root, int sum){
int res = 0;
if(root == null)
return res;
if(sum == root.val)
res++;
res += findPath(root.left, sum - root.val);
res += findPath(root.right, sum - root.val);
return res;
}

}

leetcode-1-Two Sum

Posted on 2019-09-16 | In leetcode , top-100-liked-questions |
Words count in article: 122 | Reading time ≈ 1

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

1
2
3
4
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for(int i=0; i<nums.length; i++)
{
int cur = target-nums[i];
if(map.containsKey(cur))
return new int[]{map.get(cur), i};
map.put(nums[i], i);
}
return new int[]{};
}
}

leetcode-53-Maximum Subarray

Posted on 2019-09-16 | In leetcode , top-100-liked-questions |
Words count in article: 114 | Reading time ≈ 1

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

1
2
3
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int maxSubArray(int[] nums) {
int maxret = nums[0], maxcur = nums[0];
for(int i=1; i<nums.length; i++)
{
maxcur = Math.max(maxcur+nums[i], nums[i]);
maxret = Math.max(maxret, maxcur);
}
return maxret;
}
}

leetcode-101-Symmetric Tree

Posted on 2019-09-16 | In leetcode , top-100-liked-questions |
Words count in article: 151 | Reading time ≈ 1

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

1
/ \
2 2
/ \ / \
3 4 4 3


But the following [1,2,2,null,3,null,3] is not:

1
/ \
2 2
\ \
3 3

Note:
Bonus points if you could solve it both recursively and iteratively.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return helper(root, root);
}
public boolean helper(TreeNode t1, TreeNode t2){
if(t1 == null && t2 == null) return true;
if(t1 == null || t2 == null) return false;
return (t1.val == t2.val) && helper(t1.left, t2.right) && helper(t1.right, t2.left);
}
}

leetcode-11-Container With Most Water

Posted on 2019-09-15 | In leetcode , top-100-liked-questions |
Words count in article: 146 | Reading time ≈ 1

Given n non-negative integers a1, a2, …, an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.

Example:

1
2
Input: [1,8,6,2,5,4,8,3,7]
Output: 49

1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public static int maxArea(int[] height) {
if (height == null || height.length == 0)
return 0;
int len = height.length;
int low = 0, high = len - 1, maxArea = -1;
while (low < high) {
int currentArea = (high - low) * (Integer.min(height[low], height[high]));
maxArea = Integer.max(maxArea, currentArea);
if (height[low] <= height[high])
low++;
else
high--;
}
return maxArea;
}
}

leetcode-543-Diameter of Binary Tree

Posted on 2019-09-15 | In leetcode , top-100-liked-questions |
Words count in article: 169 | Reading time ≈ 1

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

Example:

1
2
3
4
5
6
7
Given a binary tree 
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int max = 0;

public int diameterOfBinaryTree(TreeNode root) {
maxDepth(root);
return max;
}

private int maxDepth(TreeNode root) {
if (root == null) return 0;

int left = maxDepth(root.left);
int right = maxDepth(root.right);

max = Math.max(max, left + right);

return Math.max(left, right) + 1;
}
}

leetcode-121-Best Time to Buy and Sell Stock

Posted on 2019-09-15 | In leetcode , top-100-liked-questions |
Words count in article: 189 | Reading time ≈ 1

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

1
2
3
4
5
6
7
8
9
10
11
Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0)
return 0;

int buyPrice = prices[0];
int max = 0;

int len = prices.length;
for(int i=0; i<len; i++)
{
if(prices[i] < buyPrice)
buyPrice = prices[i];
else
{
int newProfit = prices[i]-buyPrice;
max = (newProfit > max ? newProfit : max);
}
}
return max;
}
}

leetcode-215-Kth Largest Element in an Array

Posted on 2019-09-11 | In leetcode , top-100-liked-questions |
Words count in article: 218 | Reading time ≈ 1

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Example 1:

1
2
Input: [3,2,1,5,6,4] and k = 2
Output: 5

Example 2:

1
2
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.

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
class Solution {
public int findKthLargest(int[] nums, int k) {
return quickSelect(nums, 0, nums.length - 1, k);
}

int quickSelect(int[] nums, int low, int high, int k) {
int pivot = low;

// use quick sort's idea
// put nums that are <= pivot to the left
// put nums that are > pivot to the right
for (int j = low; j < high; j++) {
if (nums[j] <= nums[high]) {
swap(nums, pivot++, j);
}
}
swap(nums, pivot, high);

// count the nums that are > pivot from high
int count = high - pivot + 1;
// pivot is the one!
if (count == k) return nums[pivot];
// pivot is too small, so it must be on the right
if (count > k) return quickSelect(nums, pivot + 1, high, k);
// pivot is too big, so it must be on the left
return quickSelect(nums, low, pivot - 1, k - count);
}
}

leetcode-48-Rotate Image

Posted on 2019-09-11 | In leetcode , top-100-liked-questions |
Words count in article: 217 | Reading time ≈ 1

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Note:

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

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
Example 1:

Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],

rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:

Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],

rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {
public void rotate(int[][] M) {
for (int i = 0; i < (M.length+1)/2; i++) {
for (int j = 0; j < M.length/2; j++) {
int tmp = M[i][j];
M[i][j] = M[M.length-j-1][i];
M[M.length-j-1][i] = M[M.length-i-1][M.length-j-1];
M[M.length-i-1][M.length-j-1] = M[j][M.length-i-1];
M[j][M.length-i-1] = tmp;
}
}
}
}
1…101112…38
zzm99

zzm99

372 posts
40 categories
3 tags
GitHub
0%
© 2020 zzm99 | Site words total count: 409.1k
Powered by Hexo
|
Theme — NexT.Gemini v5.1.4