leetcode:217. Contains Duplicate

bug:越界访问导致ERROR: AddressSanitizer: heap-buffer-overflow on address ==30==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x603000000054 at pc 0x00000040d6e7 bp 0x7fffd87fd2f0 sp 0x7fffd87fd2e8 READ of 越界访问了,注意数组等的边界,len-1 ==================... 阅读详情

ac了,这个比较简单,

1.先排序,

2.然后 从头扫起,遇到两个相等的说明有重复

/*
1.数组完全映射过去,
2.扫一遍,如果元素地址内的值大于1则返回true,否则返回false

*/
class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        if(nums.size()<2)return false;
        sort(nums.begin(),nums.end());
        // map<int,int> judge(nums.begin(),nums.end());
        for(auto i=0;i<nums.size()-1;i++)
        {
            if(nums[i]==nums[i+1])return true;
        }
        return false;       
    }
};

 

就想用unordered_map做一下,咋写:

1. 循环映射,+1 判断

自己写的乱七八糟:

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        int len=nums.size();
        if(len<2)return false;
        
        unordered_map<int,int> judge_map;
        unordered_map<int,int>::iterator it;
// (*it).first;             // the key value (of type Key)
// (*it).second;  
        for(auto i=0;i<len-1;i++)
        {
            // if(judge_map<nums[i]>)
            judge_map.insert(make_pair(nums[i], 0));
            printf("  %d\n",judge_map.second);
            
        }
        
        return false;
        
    }
};

 

 

看大佬的:

deck's avatar

Basic 48ms C++ solution with unordered_map

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        if (nums.empty()) { return false; }
        unordered_map<int,int> mp;
        for (int i : nums) {
            if (++mp[i] > 1) {
                return true;
            }
        }
        return false;
    }
};

 

set的也很酷,,

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        unordered_set<int> rec;
        for (auto& n : nums) {
            if (rec.find(n) != rec.end()) {
                return true;
            }
            rec.insert(n);
        }
        return false;
    }
};

 

 

 

 

值得苦练的100道Python经典练手题(全网最全,附详细答案,建议收藏) 这100道Python练习题涵盖了从基础语法到高级算法、从数据库操作到Web开发的各个方面,是备考数据库系统工程师的绝佳素材。建议按照章节顺序逐一练习,遇到难点可反复钻研,真正掌握每一道题背后的知识点。通过这些练习,不仅能提升Python编程能力,还能加深对数据库系统原理的理解,为考试和实际工作打下坚实基础。 阅读详情

相关推荐

告别迷茫!用ETAS RTA-OS配置你的第一个AUTOSAR OS任务(含VRTA虚拟ECU实战)

本文详细介绍了如何使用ETAS RTA-OS工具链在VRTA虚拟ECU上配置和运行第一个AUTOSAR OS任务。通过从XML配置到任务调度的全流程实战,帮助开发者快速掌握嵌入式操作系统开发的核心步骤,特别适合刚接触AUTOSAR的开发者快速上手。

weixin_42533622的博客 418

LeetCode: 217. Contains Duplicate

LeetCode: 217. Contains Duplicate 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 i

qha0731的专栏 390

在MDK5.37版本中添加Complier Version 5( 解决Missing Compiler Version 5 )

本文章仅作为个人学习记录,方法也是从其他博主的博客中得到的,链接如下:二、Keil——Missing Compiler Version 5 和 core_cm3.c 问题解决 - YI颗白菜 - 博客园 (cnblogs.com) 问题描述 更新最新的keil版本(MDK5.37)后,在编译以前版本的工程文件时,发现出现了非常多的报错,在网上搜索之后发现原来时编译器版本不匹配的问题,即MDK5.37中使用的是Version 6版本的编译器,而缺少Version 5,对于以前编写的工

leveling99的博客 1万+

LeetCode 217:Contains Duplicate

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

哈哈的个人专栏 7697

lvds接口_LVDS,接口,时序讲解,非常好的文章

欢迎FPGA工程师加入官方微信技术群点击蓝字关注我们FPGA之家-中国最好最大的FPGA纯工程师社群1.1.1 LVDS接口分类1.1.1.1 单路6bit LVDS这种接口电路中,采用单路方式传输,每个基色信号采用6位数据,共18位RGB数据,因此,也称18位或18bit LVDS接口。此,也称18位或18bit LVDS接口。1.1.1.2 双路6bit LVDS这种接口电...

weixin_39639286的博客 1903

3.1使用Python读取excel的二维数据

要使用 Python 读取 Excel 的二维数据,可以使用 openpyxl 或 pandas 库。

kenshin1980的专栏 1032

leetcode 217: Contains Duplicate

leetcode 217: Contains Duplicate c++ java python

西施豆腐渣 3171

使用pyqt5实现可勾选的测试用例界面

使用pyqt5实现可勾选的测试用例界面

天赐好车的博客 629

LeetCode笔记:217. Contains Duplicate

判断数组内是否有相同的数值

Minecraft 4106

Windows 镜像包大全(附百度云下载链接)

插入U盘,找到下载好的两个驱动软件,并安装,先打开驱动人生万能网卡版,安装好网卡驱动,可以接入wifi或者网线了,然后打开驱动精灵,按照提示,安装所有的驱动(中间要是让你重启,就先选择稍后再说,如果有的驱动安装好之后非要你重启,关不掉的那种,那你就重启吧),等全部安装好了,重启电脑。如果你有显卡,这里以英伟达举例,我是GTX960的,当你的驱动都安装好后,右键桌面,会出现一个英伟达控制面板。安装软碟通,下载之后,一直下一步就ok,啥也不用配置,到了最后一项点击“继续试用”即可。(下载里面的网卡版即可),

悦分享 7362

【Android性能优化】Android App 冻结与内存压缩:CachedAppOptimizer 源码级解析

本文基于 AOSP Android 16 源码,以 `CachedAppOptimizer` 为核心,深度解析 Android 对"后台缓存应用"的两大治理手段——**进程冻结(Freezer)**与**内存压缩(Compaction)**。文中完整还原冻结的 debounce 去抖动机制、`mEarliestFreezableTime` 的最早可冻结时刻算法、粘性冻结(Sticky Freeze)的语义,以及解冻时必须"先解 binder 再解进程"的顺序奥义。

weixin_44081096的博客 183

LeetCode数组专题: 217. Contains Duplicate && 219. Contains Duplicate II

“来啦来啦!!!” 217.Contains Duplicate 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. Example 1:I

qq_36010523的博客 218

数学建模算法案例精讲500篇-【深度强化学习】深度确定性策略梯度(DDPG)(附MATLAB和python代码实现)

它是一种学习连续动作的无模型策略算法。它结合了DPG(确定性策略梯度)和DQN(深度Q网络)的思想。它利用DQN中的经验重放和延迟更新的目标网络,并基于DPG,可以在连续的动作空间上运行。# 用于生成带有噪声的动作def __init__(self, action_space, mu=0.0, theta = 0.15, max_sigma = 0.3, min_sigma = 0.3, decay_period = 100000):#decay_period要根据迭代次数合理设置# 均值 mu。

qq_36130719的博客 325

leetcode:202. Happy Number

又是放弃治疗的题,,, 肯定有别的简单的方法,菜,,,已经懒得思考了 class Solution { public: bool isHappy(int n) { if(n==1) return true; int sum=0; int a=n%10; int b=n/10; sum=pow(a,2)+p...

hunter 247

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

leetcode:1. Two Sum

如何优化呢: 没考虑负数,错误,,, /* 1.寻找加起来等于某个数的两个数,返回其小标 */ class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { // sort(nums.begin(),nums.end); ...

hunter 229

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

leetcode: Reverse Linked List

我去,单链表的逆转都没搞定,,,醉了 写的啥破玩意儿,,, 还是写不出来。 能出结果,但不知道哪里错了,没被ac, 太low了。 low写法: /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(in...

hunter 223

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

leetcode:237. Delete Node in a Linked List

删节点, 题目给的条件和给的类的参数不太明白。。。 /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class So...

hunter 207

leetcode:169. Majority Element

结果貌似正确,但提交heap overflow 了,没被ac, 数组老犯这种错误。 /* 思路: 1.找出两个不同的元素的值存起来,用标记区分 2.默认tmp[0]的个数最多, */ class Solution { public: int majorityElement(vector<int>& nums) { vector<int...

hunter 199

leetcode:268. Missing Number

思路: 1.先加进map, 2.第二遍循环缺的 class Solution { public: int missingNumber(vector<int>& nums) { int len=nums.size(); if(len==0) return 0; map<int...

hunter 198

leetcode:242. Valid Anagram

想法太天真了点: 错误,容我想想, class Solution { public: bool isAnagram(string s, string t) { int len=s.length(); int len_t=t.length(); if(len!=len_t)return false; int r...

hunter 196

leetcode:171. Excel Sheet Column Number

就是26进制数转化成10进制 醉了,熬夜无法思考: 想用map帮忙,,,没会写,,,, class Solution { public: int titleToNumber(string s) { int len=s.length()-1,sum=0; map <char,int> covert_map; for(i...

hunter 194

leetcode: single number

1.[2,2,1,7,6,9,0,4,4,0,9,6,1] 思路: 1.1 假设a[0]就是dingle number, a[0]与a[1]之后的所有元素比较,直到最后一个元素。 1.2 如果中途a[0]等于其他元素,跳转出来,a[1]与后面的元素比,直到最后一个元素。 重复扫完所有元素。 瞬间方了,,,写的啥玩意儿 #include <iostream> #i...

hunter 194

leetcode:412. Fizz Buzz

思路整理: 3的倍数 Fizz 5的倍数 Buzz 3&&5 则FizzBuzz n%3==0 n%5==0 && 注意并列,提高整合,不要写多余的代码,看人家的写的多好。 抄别人的, class Solution { public: vector<string> fizzBuzz(int n) { ...

hunter 191

leetcode:101. Symmetric Tree

敢不敢把问题理清楚点???懒,写的啥破玩意儿,,,,回来继续写 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NU...

hunter 189

leetcode:122. Best Time to Buy and Sell Stock II

最佳买卖点: 写的啥,太复杂了 /* thinking: 1.get the smaller num to buy, 2.assume cur num to buy if next is smaller ,not buy, 3.when cur<before, cur<next buy, ================ for each num: buy or no...

hunter 169

leetcode:387. First Unique Character in a String

不要慌,搞懂题目先, 思路: unordered_map 映射好,然后判断: 不过好像比大家的慢了好多,为什么呢?有什么更快的呢 class Solution { public: int firstUniqChar(string s) { int len=s.length(); unordered_map<int,int> mp;...

hunter 163
上一篇: 搬:JNI编程-- undefined reference to `__android_log_print' 的解决办法
下一篇: leetcode:171. Excel Sheet Column Number
nedwons
博客等级 码龄9年 311粉丝 572原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值