Notice
Recent Posts
Recent Comments
Today
Total
01-10 18:14
Link
๊ด€๋ฆฌ ๋ฉ”๋‰ด

Partially Committed

[LEETCODE] 1502. Can Make Arithmetic Progression From Sequence ๋ณธ๋ฌธ

๐Ÿ”ฅ Algorithm || ๋ฌธ์ œํ’€์ด/PS

[LEETCODE] 1502. Can Make Arithmetic Progression From Sequence

WonderJay 2022. 10. 12. 15:12
728x90
๋ฐ˜์‘ํ˜•
SMALL

https://leetcode.com/

TITLE : 1502. Can Make Arithmetic Progression From Sequence

Description : 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.

 

Example 1:

Input: arr = [3,5,1]
Output: true
Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.

Example 2:

Input: arr = [1,2,4]
Output: false
Explanation: There is no way to reorder the elements to obtain an arithmetic progression.

 

Constraints:

  • 2 <= arr.length <= 1000
  • -106 <= arr[i] <= 106

  ๊ธธ์ด 2 ์ด์ƒ์˜ ์ •์ˆ˜๊ฐ€ ๋‹ด๊ธด ๋ฐฐ์—ด์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ์–ด๋–ป๊ฒŒ๋“  ์—ฐ์†ํ•˜๋Š” ๋‘ ์›์†Œ์˜ ์ฐจ์ด๊ฐ€ ํ•ญ์ƒ ๋™์ผํ•˜๋„๋ก ํ•  ์ˆ˜ ์žˆ์œผ๋ฉด Arithmetic progression ํ•˜๋‹ค๊ณ  ์ •์˜ํ•œ๋‹ค. ์ฃผ์–ด์ง„ ๋ฐฐ์—ด์— ๋Œ€ํ•ด์„œ Arithmetic progression ํ•œ ์ง€๋ฅผ true/false ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๋œ๋‹ค. ์ด๋ฅผ ์œ„ํ•ด ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ ๋’ค, ๊ฐ๊ฐ์˜ ์›์†Œ๋“ค๊ฐ„์˜ ์ฐจ์ด๊ฐ€ ์ผ์ •ํ•œ์ง€ ์ฒดํฌํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

 

[C++]

class Solution {
public:
    bool canMakeArithmeticProgression(vector<int>& arr) {
        sort(arr.begin(), arr.end());
        int diff = 0; int check = arr[1] - arr[0];
        for (int i = 1; i < arr.size(); i++) {
            diff = arr[i] - arr[i - 1];
            if (check != diff) return false;
        } return true;
    }
};

 

728x90
๋ฐ˜์‘ํ˜•
LIST
Comments