You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请教GeeksforGeeks中数组去重代码的特定行逻辑

Hey there! Let's break down this array deduplication code step by step—since your snippet cut off, I'll first put the full, complete code together, then explain the key lines folks usually find confusing.

Understanding the Array Deduplication Code

First, here's the full working version of the code (filling in the missing parts from your snippet):

class Main {
    // 移除重复元素的函数
    // 该函数返回修改后数组的新长度
    static int removeDuplicates(int arr[], int n) {
        // 若数组为空或仅含一个元素则直接返回
        if (n == 0 || n == 1)
            return n;

        int[] temp = new int[n];
        // 开始遍历元素
        int j = 0;

        for (int i = 0; i < n - 1; i++)
            // 若当前元素不等于下一个元素,就把当前元素存入temp数组
            if (arr[i] != arr[i + 1])
                temp[j++] = arr[i];

        // 手动添加原数组的最后一个元素
        temp[j++] = arr[n - 1];

        // 可选:将去重后的元素复制回原数组(实现原地修改效果)
        for (int i = 0; i < j; i++)
            arr[i] = temp[i];

        return j;
    }

    public static void main(String[] args) {
        int arr[] = {1, 2, 2, 3, 4, 4, 4, 5};
        int n = arr.length;

        n = removeDuplicates(arr, n);

        // 打印去重后的数组
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }
}

Key Line Explanations (Common Confusion Points)

1. Loop condition: for (int i=0; i<n-1; i++)

You might wonder why we stop at n-1 instead of n. That's because we're comparing each element arr[i] with the next element arr[i+1]. Since arrays are 0-indexed, arr[n] would be out of bounds. This loop lets us check every consecutive pair safely without hitting an error.

2. Core logic line: if (arr[i] != arr[i+1]) temp[j++] = arr[i];

This line does two critical jobs:

  • Duplicate check: We only add arr[i] to the temp array if it's not identical to the next element. This filters out consecutive duplicates.
  • Track unique count: The j++ part moves our pointer to the next empty spot in temp every time we add a unique element. By the end, j will equal the total number of unique elements.

3. Final element handling: temp[j++] = arr[n-1];

Our loop only runs up to i = n-2 (since i < n-1), which means the last element arr[n-1] never gets checked in the loop (there's no arr[n] to compare it to). But this element is either unique or the last occurrence of its value, so we have to add it manually to avoid missing it.

4. Return value j

By the end of the function, j holds the exact count of unique elements in the array—this is the new length we need to return, since the first j elements of arr (or temp) are now deduplicated.

If you had a specific line in mind that you're stuck on, feel free to point it out and I can dive even deeper!

内容的提问来源于stack exchange,提问作者Ignite

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:22:33