LeetCode 217 Contains Duplicate

本文介绍了两种有效的算法来检查一个整数数组中是否存在重复元素。第一种方法通过排序数组并比较相邻元素来实现;第二种方法则利用哈希表记录每个元素的出现次数,若某个元素出现次数超过一次,则返回真值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem:

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Summary:

判断数组中是否出现重复值。

Analysis:

1. 给数组排序后遍历,判断相邻两值是否相等。

 1 class Solution {
 2 public:
 3     bool containsDuplicate(vector<int>& nums) {
 4         int len = nums.size();
 5         
 6         sort(nums.begin(), nums.end());
 7         for (int i = 1; i < len; i++) {
 8             if (nums[i] == nums[i - 1]) {
 9                 return true;
10             }
11         }
12         
13         return false;
14     }
15 };

2. Hash表建立数组中数字和出现次数的映射,判断是否大于1。

 1 class Solution {
 2 public:
 3     bool containsDuplicate(vector<int>& nums) {
 4         int len = nums.size();
 5         unordered_map<int, int> m;
 6         
 7         for (int i = 0; i < len; i++) {
 8             if(++m[nums[i]] > 1) {
 9                 return true;
10             }
11         }
12         
13         return false;
14     }
15 };

转载于:https://www.cnblogs.com/VickyWang/p/6012319.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值