본문 바로가기

Algorithm/Brute Force

(C++) - LeetCode (easy) 1385. Find the Distance Value Between Two Arrays

반응형

https://leetcode.com/problems/find-the-distance-value-between-two-arrays/description/

 

Find the Distance Value Between Two Arrays - LeetCode

Can you solve this real interview question? Find the Distance Value Between Two Arrays - Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays. The distance value is defined as the number of elements ar

leetcode.com

전수조사 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

정답 변수 cnt를 선언 후 0으로 초기화합니다.

📔 풀이과정

arr1의 원소별 arr2에 대해 loop를 수행하며 다음을 수행합니다.

1. 지역 변수 flag를 선언후 1로 초기화해줍니다.

2. arr2의 원소들과 현재 arr1의 거리가 d이하라면 arr1은 조건에 부합하지 않으므로 flag = 0해줍니다.

3. arr1의 현재 원소에서 arr2의 모든 원소와의 거리가 d 초과라면 조건에 부합하므로 flag는 0이 되어있지 않습니다. 따라서 flag를 더해줍니다.

📔 정답 출력 | 반환

cnt를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    int findTheDistanceValue(vector<int>& arr1, vector<int>& arr2, int d) {
        int cnt = 0;
        for(auto a: arr1) {
            int flag = 1;
            for(auto b : arr2) {
                if (abs(b-a) <= d) {
                    flag = 0; 
                    break;
                }
            }
            cnt += flag;
        }
        return cnt;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.