搜索int阵列中的数字组,而无需使用循环

发布于 2025-02-02 05:19:47 字数 144 浏览 6 评论 0原文

我有以下数组

int [] a = {4、5、5、5、4、3};

我想搜索阵列以获取平面序列, 并返回阵列中最长的扁平序列。

对于此数组,答案是3(5,6,5)

是否有没有使用循环的方法?

I have the following array

int[] a = { 4, 5, 6, 5, 4, 3 };

i would like to search the array for the flat sequences,
and return the longest flat sequence in the array.

for this array the answer would be 3 (5,6,5)

is there a way to do it without using a loop?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雨落□心尘 2025-02-09 05:19:47

从技术上讲,您可以使用递归,但这并不能真正摆脱循环。您只是不编写或 的关键字

public static void main(String[] args) {
        int[] a = { 4, 5, 6, 5, 4, 3 };
        System.out.println(sequenceRecursive(a, 0, 0, 0));
    }

    public static int sequenceRecursive(int[] arr, int startIndex, int longest, int sequence) {
        if(startIndex <= 0) startIndex = 1;
        if(startIndex >= arr.length) return longest + 1;
        if(arr[startIndex] > arr[startIndex - 1]){
            sequence++;
            if(sequence > longest) longest = sequence;
        }else{
            sequence = 0;
        }
        return sequenceRecursive(arr, ++startIndex, longest, sequence);
    }

Technically you can use recursion but that doesn't really gets rid of a loop. You just dont write the keyword while or for

public static void main(String[] args) {
        int[] a = { 4, 5, 6, 5, 4, 3 };
        System.out.println(sequenceRecursive(a, 0, 0, 0));
    }

    public static int sequenceRecursive(int[] arr, int startIndex, int longest, int sequence) {
        if(startIndex <= 0) startIndex = 1;
        if(startIndex >= arr.length) return longest + 1;
        if(arr[startIndex] > arr[startIndex - 1]){
            sequence++;
            if(sequence > longest) longest = sequence;
        }else{
            sequence = 0;
        }
        return sequenceRecursive(arr, ++startIndex, longest, sequence);
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文