LeetCode 217.存在重复元素

从2022.2.28开始,本人开始LeetCode的刷题之旅
首先用的刷题指南是数据结构的14天的简易刷题计划
博客仅供本人记录刷题之旅。

原题链接如下:​
217. 存在重复元素

题解1(采用c++中set):

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        //首先用哈希表的办法
        unordered_set<int> s;
        for(int num:nums){
            if(s.count(num)){
                return true;
            }
            s.insert(num);
        }
        return false;
    }
};
提交结果:

执行用时:68 ms, 在所有 C++ 提交中击败了70.58%的用户

内存消耗:50.2 MB, 在所有 C++ 提交中击败了26.78%的用户

通过测试用例:69 / 69

题解2(采用java中的hashset):

class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<Integer>();
        for(int num:nums){
            //只需要校验一次add操作失败即可
            if(!set.add(num)){
                return true;
            }
        }
        return false;
    }
}
//低配版:
public boolean containsDuplicate(int[] nums) {
        Set<Integer> res = new HashSet<Integer>();
        for(int i:nums)
            res.add(i);
        return res.size()<nums.length?true:false;
 //

题解3(python中的set,一行搞定):

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        return len(nums)!=len(set(nums));

题解4(先排序):

(77条消息) C++中sort()函数的使用方法_kuimzzs的博客-CSDN博客_c++中sort

(77条消息) C++ 中vector的使用方法_那年聪聪-CSDN博客_c++vector

背景知识相关代码介绍如下:

//背景知识:
//sort()是C++给的一种排序函数,头文件为 #include <algorithm> 
//语法描述:sort(begin,end,cmp),cmp参数可以没有,如果没有默认非降序排序。

//从小到大排序(默认)
#include <iostream>
#include <algorithm>
 
using namespace std;
 
int main()
{
    int a[] = {9,5,2,7,6,1,3};
    sort(a,a+7);//也就是sort(begin,end),第三个参数没有 默认升序排序
    for(int i = 0;i < 7; ++i)
    {
        cout<<a[i];    
    }
    cout<<endl;
    return 0;
}
//输出结果:1235679

//使用指定的方式升序排序
#include <iostream>
#include <algorithm>
 
using namespace std;
 
//这里需要我们手写排序逻辑函数func
bool func(int i,int j){
    return i>j//也就是左边的数字必须大于右边的数字才是true
}
 
int main()
{
    int a[] = { 9,5,2,7,6,1,3 };
    sort(a, a + 7,func);
    for (int i = 0; i < 7; ++i)
    {
        cout << a[i];
    }
    cout << endl;
    return 0;
}
//输出结果:9765321
    
    

解题代码如下:

注:由于题解代码中用到了c++ STL中的vector容器,所以本人在这里也介绍了一下有关vector的背景知识

(77条消息) C++ 中vector的使用方法_那年聪聪-CSDN博客_c++vector

(77条消息) C++STL中vector容器 begin()与end()、front()与back()、find()函数的用法_那年聪聪-CSDN博客

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        sort(nums.begin(),nums.end());//这就是上述背景知识中介绍的c++中的sort()函数
        for(int i=0;i<nums.size()-1;i++){//注意一下这里容易越界,应该是<size-1,不然下面那个i+1会越界
            if(nums[i] == nums[i+1]){
                return true;
            }
        }
        return false;
    }
};

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值