LeetCode 1502. Can Make Arithmetic Progression From Sequence
考点 | 难度 |
---|---|
Sorting | 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
.
思路
先对arr
排序,检查相邻的两个数是不是差一样。
答案
public boolean canMakeArithmeticProgression(int[] arr) {
Arrays.sort(arr);
int difference = arr[1]-arr[0];
for(int itr = 2; itr < arr.length; itr++){
if(arr[itr]-arr[itr-1] != difference) return false;
}
return true;
}