[코테 풀이] Can Make Arithmetic Progression From Sequence

시내·2024년 6월 7일
0

Q_1502) Can Make Arithmetic Progression From Sequence

출처 : https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/?envType=study-plan-v2&envId=programming-skills

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.

class Solution {
    public boolean canMakeArithmeticProgression(int[] arr) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        for (int a : arr) {
            arrayList.add(a);
        }
        Collections.sort(arrayList);
        int subtracted = arrayList.get(1) - arrayList.get(0);
        if (arrayList.size() == 2) {
            return true;
        }
        for (int i = 1; i < arrayList.size() - 1; i++) {
            if (subtracted != arrayList.get(i + 1) - arrayList.get(i)) {
                return false;
            }
        }
        return true;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글