---
# System prepended metadata

title: 1502. Can Make Arithmetic Progression From Sequence
tags: [Leetcode, Easy, Arithmetic Sequence]

---

# 1502. Can Make Arithmetic Progression From Sequence
###### tags: `Leetcode` `Easy` `Arithmetic Sequence`
Link: https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/
## 思路
### 思路一 $O(NlogN)$ $O(1)$
排序
### 思路二 $O(N)$ $O(N)$
遍历一遍，找到最大和最小值，将每个数存到set里面，如果最大值和最小值的差不能被元素个数-1整除，那么就return false，接着从最小值开始检查，是不是每个+diff（最大最小值的差除以元素个数-1）的结果都在set里面，如果有一个不在就return false
要注意的是有可能diff = 0，这时候如果set里面只有一个元素，就是true
## Code
### 思路一
```java=
class Solution {
    public boolean canMakeArithmeticProgression(int[] arr) {
        Arrays.sort(arr);
        int diff = arr[1]-arr[0];
        for(int i = 2;i < arr.length;i++){
            if(arr[i]!=arr[i-1]+diff){
                return false;
            }
        }
        return true;
    }
}
```
### 思路二
```java=
class Solution {
    public boolean canMakeArithmeticProgression(int[] arr) {
        int minVal = Integer.MAX_VALUE, maxVal = Integer.MIN_VALUE;
        Set<Integer> exist = new HashSet<>();
        for(int i = 0;i < arr.length;i++){
            minVal = Math.min(minVal, arr[i]);
            maxVal = Math.max(maxVal, arr[i]);
            exist.add(arr[i]);
        }
        int diff;
        if((maxVal-minVal)%(arr.length-1)!=0){
            return false;
        }
        else{
            diff = (maxVal-minVal)/(arr.length-1);
        }
        if(diff == 0){
            if(exist.size()==1) return true;
            else return false;
        }
        int temp = minVal;
        while(temp <= maxVal){
            if(!exist.contains(temp)){
                return false;
            }
            temp += diff;
        }
        return true;
    }
}
```