Compare commits

...

3 Commits

Author SHA1 Message Date
Gleb Koval dd88ef2c57
count-good-nodes-in-binary-tree 2022-09-01 18:10:51 +00:00
Gleb Koval 5edf7fa141
3-sum-closest 2022-09-01 17:06:45 +00:00
Gleb Koval cbcd0a685a
cleanup 2022-09-01 12:41:00 +00:00
6 changed files with 92 additions and 2 deletions

View File

@ -4,6 +4,8 @@
ARG VARIANT="buster"
FROM mcr.microsoft.com/vscode/devcontainers/base:0-${VARIANT}
RUN sudo apt install gnupg2 -y
# ** [Optional] Uncomment this section to install additional packages. **
# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
# && apt-get -y install --no-install-recommends <your-package-list-here>

View File

@ -14,7 +14,8 @@
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"rust-lang.rust-analyzer"
"rust-lang.rust-analyzer",
"LeetCode.vscode-leetcode"
],
// Use 'forwardPorts' to make a list of ports inside the container available locally.

4
.gitignore vendored
View File

@ -1 +1,3 @@
/target
/target
Cargo.lock
Cargo.toml

8
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,8 @@
{
"leetcode.filePath": {
"default": {
"folder": "${kebab-case-name}",
"filename": "sol.${ext}"
}
}
}

33
3-sum-closest/sol.rs Normal file
View File

@ -0,0 +1,33 @@
/*
* @lc app=leetcode id=16 lang=rust
*
* [16] 3Sum Closest
*/
struct Solution {}
// @lc code=start
use std::cmp::Ordering;
impl Solution {
pub fn three_sum_closest(mut nums: Vec<i32>, target: i32) -> i32 {
nums.sort_unstable();
let mut result = nums[0] + nums[1] + nums[2];
for (i, &n) in nums.iter().enumerate() {
let (mut l, mut r) = (i + 1, nums.len() - 1);
while l < r {
let sum = n + nums[l] + nums[r];
if (target - sum).abs() < (target - result).abs() {
result = sum;
}
match sum.cmp(&target) {
Ordering::Equal => return sum,
Ordering::Less => l += 1,
Ordering::Greater => r -= 1
}
}
}
result
}
}
// @lc code=end

View File

@ -0,0 +1,44 @@
/*
* @lc app=leetcode id=1448 lang=golang
*
* [1448] Count Good Nodes in Binary Tree
*/
package main
// @lc code=start
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
import "math"
func goodNodes(root *TreeNode) int {
return subGoodNodes(root, math.MinInt)
}
func subGoodNodes(root *TreeNode, previousMax int) int {
if root == nil {
return 0
}
sum := 0
max := previousMax
if root.Val >= previousMax {
sum = 1
max = root.Val
}
sum += subGoodNodes(root.Left, max)
sum += subGoodNodes(root.Right, max)
return sum
}
// @lc code=end
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}