【数组去重】Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

题意:数组去重

解法:O(n)遍历数组,固定住一个值,将该值放入新数组中,同时遍历index往前推

public class Solution {
    public int removeDuplicates(int[] A) {
        if(A == null || A.length == 0) return 0;
        
        int len = A.length;
        int k = 0;
        int i=0;
        while(i<len){
            int t = A[i];
            A[k++] = t;
            while(++i<len && A[i] == t);
        }
        return k;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C语言中,可以通过编写一个数组去重函数来实现对数组中重复元素的去除。以下是一个示例的数组去重函数调用的介绍: 假设我们有一个整型数组`arr`,长度为`n`,我们想要对该数组进行去重操作。可以按照以下步骤进行: 1. 定义一个新的数组`result`,用于存储去重后的元素。 2. 遍历原始数组`arr`,逐个检查每个元素是否已经存在于`result`数组中。 3. 如果当前元素不存在于`result`数组中,则将其添加到`result`数组中。 4. 最后,`result`数组中存储的就是去重后的元素。 下面是一个示例的C语言代码,展示了如何调用一个数组去重函数: ```c #include <stdio.h> // 数组去重函数 int* removeDuplicates(int* arr, int n, int* resultSize) { int* result = (int*)malloc(n * sizeof(int)); // 分配内存空间 int count = 0; // 记录去重后的元素个数 for (int i = 0; i < n; i++) { int j; for (j = 0; j < count; j++) { if (arr[i] == result[j]) { break; // 当前元素已存在于result数组中,跳出内层循环 } } if (j == count) { result[count++] = arr[i]; // 当前元素不存在于result数组中,添加到result数组中 } } *resultSize = count; // 更新去重后的元素个数 return result; } int main() { int arr[] = {1, 2, 3, 2, 4, 1, 5}; int n = sizeof(arr) / sizeof(arr[0]); int resultSize; int* result = removeDuplicates(arr, n, &resultSize); printf("去重后的数组:"); for (int i = 0; i < resultSize; i++) { printf("%d ", result[i]); } free(result); // 释放内存空间 return 0; } ``` 运行上述代码,输出结果为: ``` 去重后的数组:1 2 3 4 5 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值