Press "Enter" to skip to content

Posts tagged as “hard”

花花酱 LeetCode 321. Create Maximum Number

Problem:

Given two arrays of length m and n with digits 0-9 representing two numbers. Create the maximum number of length k <= m + n from digits of the two. The relative order of the digits from the same array must be preserved. Return an array of the k digits. You should try to optimize your time and space complexity.

Example 1:

nums1 = [3, 4, 6, 5]
nums2 = [9, 1, 2, 5, 8, 3]
k = 5
return [9, 8, 6, 5, 3]

Example 2:

nums1 = [6, 7]
nums2 = [6, 0, 4]
k = 5
return [6, 7, 6, 0, 4]

Example 3:

nums1 = [3, 9]
nums2 = [8, 9]
k = 3
return [9, 8, 9]



题目大意:给你两个数字数组和k,返回从两个数组中选取k个数字能够组成的最大值。

Idea: Greedy + DP

Solution:

Time complexity: O(k * (n1+n2)^2)

Space complexity: O(n1+n2)

C++

Java

花花酱 LeetCode 4. Median of Two Sorted Arrays

题目大意:求两个已经排序的数组的中位数(如果合并后)。

Problem:

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Example 1:

Example 2:



Idea:

Binary Search

Time complexity: O(log(min(n1,n2)))

Space complexity: O(1)

 

Solution: Binary Search

C++

Java

Related Problem:

花花酱 LeetCode 149. Max Points on a Line

Problem:

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.



Idea:

count by slope

Time complexity: O(n^2)

Space complexity: O(n)

Solution:

C++ / pair

C++ / long

花花酱 LeetCode 124. Binary Tree Maximum Path Sum

Problem:

Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

For example:
Given the below binary tree,

Return 6.



Idea:

Recursion

Time complexity O(n)

Space complexity O(h)

Solution: Recursion

C++

Python3

Related Problems:

花花酱 LeetCode 128. Longest Consecutive Sequence

 

Problem:

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.



Idea:

Hashtable / Hashset

 

Time complexity: O(n)

Space complexity: O(n)

Solution 1: C++ / online

 

Solution 2: C++ / offline