Press "Enter" to skip to content

Posts tagged as “medium”

花花酱 LeetCode 15. 3Sum

题目大意:给你一个数组,让你找出3个数的和为0的所有组合。

Problem:

https://leetcode.com/problems/3sum/description/

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

Solution 1: Hashtable

Time complexity: O(n^2)
Space complexity: O(n)

Solution 2: Sorting + Two pointers

Time complexity: O(nlogn + n^2)

Space complexity: O(1)

C++

Related Problems:

花花酱 LeetCode 515. Find Largest Value in Each Tree Row

题目大意:给你一棵树,返回每一层最大的元素的值。

You need to find the largest value in each row of a binary tree.

Example:

Solution 1: Inorder traversal + depth info

C++

Python3

 

花花酱 LeetCode 513. Find Bottom Left Tree Value

题目大意:给你一棵树,返回左下角(最后一行最左面)的节点的值。

https://leetcode.com/problems/find-bottom-left-tree-value/description/

Problem:

Given a binary tree, find the leftmost value in the last row of the tree.

Example 1:

Example 2: 

Note: You may assume the tree (i.e., the given root node) is not NULL.

Solution 1: Inorder traversal with depth info

The first node visited in the deepest row is the answer.

Python3

 

 

花花酱 LeetCode 792. Number of Matching Subsequences

题目大意:给你一些单词,问有多少单词出现在字符串S的子序列中。

https://leetcode.com/problems/number-of-matching-subsequences/description/

Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S.

Note:

  • All words in words and S will only consists of lowercase letters.
  • The length of S will be in the range of [1, 50000].
  • The length of words will be in the range of [1, 5000].
  • The length of words[i] will be in the range of [1, 50].

Solution 1: Brute Force

Time complexity: O((S + L) * W)

C++ w/o cache TLE

Space complexity: O(1)

C++ w/ cache 155 ms

Space complexity: O(W * L)

Solution 2: Indexing+ Binary Search

Time complexity: O(S + W * L * log(S))

Space complexity: O(S)

S: length of S

W: number of words

L: length of a word

C++

Java

 

Python 3:

w/o cache

w/ cache

 

花花酱 LeetCode 795. Number of Subarrays with Bounded Maximum

题目大意:问一个数组中有多少个子数组的最大元素值在[L, R]的范围里。

We are given an array A of positive integers, and two positive integers L and R (L <= R).

Return the number of (contiguous, non-empty) subarrays such that the value of the maximum array element in that subarray is at least L and at most R.

Solution 1:

C++

Solution 2: One pass

C++