leetcode - longest common subsequence between sorted arrays(java)

silver·2021년 7월 2일

level - medium

[문제 내용]
주어진 배열에서 공통된 배열을 찾아서 반환

[example 1]

Input: arrays = [[1,3,4],
               [1,4,7,9]]
Output: [1,4]
Explanation: The longest subsequence which 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 subsequence which in all of the 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.

[해결 방법]
주어진 배열에서 먼저 처음 두개의 배열의 공통된 것을 찾고
그다음 배열과 비교할때는 먼저 찾은 공통된 숫자들과 비교하여
최종적으로 공통된 숫자들만 남게하여 해결하였다.

class Solution {
    public List<Integer> longestCommomSubsequence(int[][] arrays) {
        ArrayList<Integer> comparison = new ArrayList<>();
        // 처음 비교할 대상으로 주어진 배열중 가장 첫번째를 선택한다.
        for(int i=0; i<arrays[0].length; i++) {
            comparison.add(arrays[0][i]);
        }
        
        // 다음 배열을 가져와 비교
        for(int i=1; i<arrays.length; i++) {
            // 공통 숫자의 index를 저장할 변수
            ArrayList<Integer> index = new ArrayList<>();
            for(int j=0; j<arrays[i].length; j++) {
                if(comparison.contains(arrays[i][j])) {
                    index.add(comparison.indexOf(arrays[i][j]));
                }
            }
            ArrayList<Integer> buffer = new ArrayList<>();
            for(int j : index) {
                buffer.add(comparison.get(j));
            }
            // 비교 대상을 찾은 공통된 숫자로 변경
            comparison = buffer;
        }
        
        return comparison;
    }
}

0개의 댓글