Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to judge whether the isometric sequence can be formed by LeetCode

Shulou Source: shulou.com Published: 2022-06-01 13:03:16 09月15日 Update

This article mainly shows you "how LeetCode judges whether an arithmetic series can be formed". The content is simple and easy to understand, and the organization is clear. I hope it can help you solve your doubts. Let Xiaobian lead you to study and learn this article "how LeetCode judges whether an arithmetic series can be formed".

1. Determine whether the arithmetic series can be formed. 1. Brief description of the problem

Give you an array of numbers arr.

If the difference between any two adjacent terms in a sequence is always equal to the same constant, then the sequence is called an arithmetic sequence.

Returns true if the array can be rearranged to form an arithmetic series; otherwise, returns false.

Arithmetic series of content in our high school period is also a common problem, encountered here, on the use of procedures to solve it

2, example brief description example 1:

Input: arr = [3,5,1]

Output: true

Explanation: Reordering the array results in [1,3,5] or [5,3,1], and the difference between any two adjacent terms is 2 or-2, respectively, which can form an arithmetic sequence.

Example 2:

Input: arr = [1,2,4]

Output: false

Explanation: Arithmetic progression cannot be obtained by reordering.

3, the solution to the problem

Based on arithmetic progression calculations.

4, the solution program

import java.util.Arrays;

public class CanMakeArithmeticProgressionTest {

public static void main(String[] args) {

int[] arr = {1, 3, 5, 7};

boolean canMakeArithmeticProgression = canMakeArithmeticProgression(arr);

System.out.println("canMakeArithmeticProgression = " + canMakeArithmeticProgression);

}

public static boolean canMakeArithmeticProgression(int[] arr) {

if (arr == null) {

return false;

}

Arrays.sort(arr);

int a1 = arr[0];

int a2 = arr[1];

int value = a2 - a1;

for (int i = 1; i < arr.length; i++) {

if (arr[i] - arr[i - 1] != value) {

return false;

}

}

return true;

}

}

The above is "LeetCode how to judge whether the formation of arithmetic series" all the content of this article, thank you for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to the industry information channel!

Tags: Series isometric series equidifference content arrays examples articles programs problem solutions learning help sorting interpretation input output one constant common ideas numbers Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS OPPO Reno MariaDB Apple Redmi