zoukankan      html  css  js  c++  java
  • [LeetCode] 1940. Longest Common Subsequence Between Sorted Arrays

    Given an array of integer arrays arrays where each arrays[i] is sorted in strictly increasing order, return an integer array representing the longest common subsequence between all the arrays.

    A subsequence is a sequence that can be derived from another sequence by deleting some elements (possibly none) without changing the order of the remaining elements.

    Example 1:

    Input: arrays = [[1,3,4],
                     [1,4,7,9]]
    Output: [1,4]
    Explanation: The longest common subsequence in the two arrays is [1,4].
    

    Example 2:

    Input: arrays = [[2,3,6,8],
                     [1,2,3,5,6,7,10],
                     [2,3,4,6,9]]
    Output: [2,3,6]
    Explanation: The longest common subsequence in all three arrays is [2,3,6].
    

    Example 3:

    Input: arrays = [[1,2,3,4,5],
                     [6,7,8]]
    Output: []
    Explanation: There is no common subsequence between the two arrays.

    Constraints:

    • 2 <= arrays.length <= 100
    • 1 <= arrays[i].length <= 100
    • 1 <= arrays[i][j] <= 100
    • arrays[i] is sorted in strictly increasing order.

    排序数组之间的最长公共子序列。

    给定一个由整数数组组成的数组 arrays,其中 arrays[i] 是严格递增排序的,返回一个表示所有数组之间的最长公共子序列的整数数组。

    子序列是从另一个序列派生出来的序列,删除一些元素或不删除任何元素,而不改变其余元素的顺序。

    这道题我给出一个类似 counting sort 的思路。同时这道题跟最长公共子序列这个LC常考的考点没什么太大关系。

    注意题目给的二维数组并不是一个完美的矩阵,每一行的元素个数并不是一样的。同时注意题目给定的元素区间是 [1, 100],所以我可以创建一个长度为 101 的数组 map,之后开始遍历一遍这个二维数组,统计一下每个数字都出现了几次。因为题目问的是统计所有数组中出现的最长公共子序列,而且每个子数组又保持递增,所以当我们统计完毕之后,去 map 里找出现次数 == 子数组个数的数字,即是题目要求的数字。

    时间O(n^2)

    空间O(n)

    Java实现

     1 class Solution {
     2     public List<Integer> longestCommonSubsequence(int[][] arrays) {
     3         int[] map = new int[101];
     4         for (int[] row : arrays) {
     5             for (int n : row) {
     6                 map[n]++;
     7             }
     8         }
     9         
    10         List<Integer> res = new ArrayList<>();
    11         for (int number = 1; number <= 100; number++) {
    12             if (map[number] == arrays.length) {
    13                 res.add(number);
    14             }
    15         }
    16         return res;
    17     }
    18 }

    LeetCode 题目总结

  • 相关阅读:
    PAT (Basic Level) Practice (中文)1002 写出这个数 (20 分)
    PAT (Advanced Level) Practice 1001 A+B Format (20 分)
    BP神经网络(原理及MATLAB实现)
    问题 1676: 算法2-8~2-11:链表的基本操作
    问题 1744: 畅通工程 (并查集)
    链表的基本操作(创建链表,查询元素,删除元素,插入元素等)
    问题 1690: 算法4-7:KMP算法中的模式串移动数组
    问题 1923: [蓝桥杯][算法提高VIP]学霸的迷宫 (BFS)
    Hdu1372 Knight Moves (BFS)
    Problem 2285 迷宫寻宝 (BFS)
  • 原文地址:https://www.cnblogs.com/cnoodle/p/15628851.html
Copyright © 2011-2022 走看看