[ Array ] - 数组去重

34 篇文章 0 订阅
3 篇文章 0 订阅

题目:

  • 如传入的数组元素为[123, "meili", "123", "mogu", 123],则输出:[123, "meili", "123", "mogu"]
  • 如传入的数组元素为[123, [1, 2, 3], [1, "2", 3], [1, 2, 3], "meili"],则输出:[123, [1, 2, 3], [1, "2", 3], "meili"]
  • 如传入的数组元素为[123, {a: 1}, {a: {b: 1}}, {a: "1"}, {a: {b: 1}}, "meili"],则输出:[123, {a: 1}, {a: {b: 1}}, {a: "1"}, "meili"]
function dis(arr) {
    const resObj = {};
    const res = [];
    arr.forEach((item) => {
        const key = item + JSON.stringify(item); //定义唯一的key 
        if (!resObj[key]) { //检测resObj中是否存在唯一的key
            res.push(item); //把唯一的key放在数组中
            resObj[key] = item; //唯一的数值存在变量中缓存起来
        }
    })
    console.log(resObj)
    return res;
}

const test1 = [123, "meili", "123", "mogu", 123,"mogu"];
const test2 = [123, [1, 2, 3], [1, "2", 3], [1, 2, 3], "meili"];
const test3 = [123, { a: 1 }, { a: { b: 1 } }, { a: "1" }, { a: { b: 1 } }, "meili"];

console.log(dis(test1)); //[123, "meili", "123", "mogu"]

console.log(dis(test2)); //[123, [1, 2, 3], [1, "2", 3], "meili"]

console.log(dis(test3)); //[123, {a: 1}, {a: {b: 1}}, {a: "1"}, "meili"]

 

在C语言中,由于原生数组不支持直接的元素去重操作,我们需要手动遍历并创建一个新的数组来存储唯一值。这里有一个简单的示例,展示了如何通过遍历和插入新数组的方式来实现数组去重: ```c #include <stdio.h> #include <stdbool.h> // 去重函数 void remove_duplicates(int arr[], int n, int unique[]) { // 确保unique数组足够大来容纳所有唯一元素 if (n > sizeof(unique) / sizeof(unique[0])) { printf("Error: Unique array is too small.\n"); return; } for (int i = 0; i < n; i++) { bool is_duplicate = false; for (int j = 0; j < i; j++) { // 避免重复比较自身 if (arr[i] == arr[j]) { is_duplicate = true; break; } } if (!is_duplicate) { unique[j] = arr[i]; // 如果不是重复,插入到unique数组中 j++; // 更新j的位置,因为找到了一个位置 } } } int main() { int source[] = {1, 2, 3, 4, 4, 5, 6, 6, 7}; int n = sizeof(source) / sizeof(source[0]); int unique[n]; // 假设unique数组足够大 remove_duplicates(source, n, unique); printf("Unique elements in the original array:\n"); for (int i = 0; i < n; i++) { printf("%d ", unique[i]); } printf("\n"); return 0; } ``` 在这个例子中,`remove_duplicates` 函数会检查源数组中的每个元素是否已经在目标数组`unique`中,如果没有则添加。注意这只是一个基本的解决方案,并非最高效,如果需要处理大数据集,更高效的算法如哈希表(如`unordered_set`)可能会更适合。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值