넘치게 채우기

[LeetCode] 1502. Can Make Arithmetic Progression From Sequence 본문

PS/LeetCode

[LeetCode] 1502. Can Make Arithmetic Progression From Sequence

riveroverflow 2023. 6. 6. 11:54
728x90
반응형

https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/description/

 

Can Make Arithmetic Progression From Sequence - LeetCode

Can you solve this real interview question? Can Make Arithmetic Progression From Sequence - A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same. Given an array of numbers arr, return

leetcode.com

문제 유형 : 수학

문제 난이도 : Easy

 

문제

A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.

Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false.

 

 주어지는 배열이 재배치되어 등차수열을 만들 수 있으면 true를 반환하고, 그렇지 않으면 false를 반환하라.

 

풀이

기본 라이브러리를 이용하여 sort해준다. i = 0부터 시작해서 i번과 i+1번째수의 차이가 일정하지 않으면 false를 반환한다.

배열을 다 돌면 true를 반환해준다.

 

코드(C++)

class Solution {
public:
    bool canMakeArithmeticProgression(vector<int>& arr) {
        int diff = 0;
        int curr_diff = 0;

        sort(arr.begin(), arr.end());

        for(int i = 0; i < arr.size()-1; i++){
            curr_diff = arr[i] - arr[i+1];

            if(i == 0){
                diff = curr_diff;
                continue;
            } 
            if(curr_diff!= diff) return false;
        }

        return true;
    }
};
 
 
728x90
반응형