413. Arithmetic Slices

LeetCode medium original: C# #array #csharp #leetcode #medium #two-pointers
Der Aufgabentext wird für die gewählte Sprache aus dem Russischen übersetzt. Code bleibt unverändert.

Ganzzahl Array называется арифметическим, если он состоит не менее чем из трех elementов и если разность между любыми двумя последовательными elementами одинакова. НаBeispiel, [1,3,5,7,9], [7,7,7] и [3,-1,-5,-9] являются арифметическими последовательностями. Если задан Ganzzahl Array nums, return количество арифметических подArrayов Arrayа nums. ПодArray - это непрерывная subsequence Arrayа.

Beispiel:

Input: nums = [1,2,3,4]

Output: 3

C# Lösung

zugeordnet/original
public class Solution {
    public int NumberOfArithmeticSlices(int[] nums) {
        if (nums.Length < 3) return 0;
        int count = 0;
        int currentLength = 0;
        for (int i = 2; i < nums.Length; i++) {
            if (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) {
                currentLength++;
                count += currentLength;
            } else {
                currentLength = 0;
            }
        }
        return count;
    }
}

C++ Lösung

Auto-Entwurf, vor dem Einreichen prüfen
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public int NumberOfArithmeticSlices(vector<int>& nums) {
        if (nums.size() < 3) return 0;
        int count = 0;
        int currentLength = 0;
        for (int i = 2; i < nums.size(); i++) {
            if (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) {
                currentLength++;
                count += currentLength;
            } else {
                currentLength = 0;
            }
        }
        return count;
    }
}

Java Lösung

zugeordnet/original
public class Solution {
    public int numberOfArithmeticSlices(int[] nums) {
        if (nums.length < 3) return 0;
        int count = 0;
        int currentLength = 0;
        for (int i = 2; i < nums.length; i++) {
            if (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) {
                currentLength++;
                count += currentLength;
            } else {
                currentLength = 0;
            }
        }
        return count;
    }
}

JavaScript Lösung

zugeordnet/original
function numberOfArithmeticSlices(nums) {
    let count = 0;
    let currentLength = 0;
    for (let i = 2; i < nums.length; i++) {
        if (nums[i] - nums[i - 1] === nums[i - 1] - nums[i - 2]) {
            currentLength++;
            count += currentLength;
        } else {
            currentLength = 0;
        }
    }
    return count;
}

Python Lösung

zugeordnet/original
def numberOfArithmeticSlices(nums):
    count = 0
    current_length = 0
    for i in range(2, len(nums)):
        if nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]:
            current_length += 1
            count += current_length
        else:
            current_length = 0
    return count

Go Lösung

zugeordnet/original
package main

func numberOfArithmeticSlices(nums []int) int {
    count := 0
    currentLength := 0
    for i := 2; i < len(nums); i++ {
        if nums[i]-nums[i-1] == nums[i-1]-nums[i-2] {
            currentLength++
            count += currentLength
        } else {
            currentLength = 0
        }
    }
    return count
}

Algorithm

Пройдите по Arrayу, инициализируя два указателя: начальный и текущий. Начните с первой пары elementов.

Для каждой пары elementов проверяйте, сохраняется ли разность между последовательными elementами. Если да, увеличивайте длину текущей арифметической последовательности. Если нет, сбрасывайте начальную позицию и начинайте новую последовательность.

Суммируйте количество найденных арифметических подArrayов, given, что для каждого арифметического подArrayа длины len, количество таких подArrayов равно (len - 2).

😎

Stellen zu dieser Aufgabe

aktive Stellen with overlapping task tags are angezeigt.

Alle Stellen
Es gibt noch keine aktiven Stellen.