[LeetCode] make Two Arrays Equal by Reversing Subarrays

아르당·약 3시간 전

LeetCode

목록 보기
305/305
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

길이가 같은 두 개의 정수 배열 target과 arr이 주어진다. 한 단계로, arr의 비어 있지 않은 부분 배열을 선택해서 역순으로 만들 수 있다. 단계 수는 제한이 없다.

target과 arr를 같게 만들수 있다면 true를 그렇지 않다면 false를 반환해라.

Example

#1
Input: target = [1, 2, 3, 4], arr = [2, 4, 1, 3]
Output: true

#2
Input: target = [7], arr = [7]
Output: true

#3
Input: target = [3, 7, 9], arr = [3, 7, 11]
Output: false

Constraints

  • target.length == arr.length
  • 1 <= target.length <= 1000
  • 1 <= target[i] <= 1000
  • 1 <= arr[i] <= 1000

Solved

class Solution {
    public boolean canBeEqual(int[] target, int[] arr) {
        int[] elementCount = new int[1001];
        int uniqueCount = 0;

        for(int i = 0; i < target.length; i++){
            if(elementCount[target[i]]++ == 0){
                uniqueCount++;
            }

            if(elementCount[arr[i]]-- == 1){
                uniqueCount--;
            }
        }

        return uniqueCount == 0;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글